Search code examples
servletshttp-status-code-404web.xmlpath-parameter

Running methods depending JSP link using switch statements on Servlets


Hi there I am fairly new to building web pages using JSP and servlets and I'm trying to use switch statements to run functions depending on the link/button the user clicks but every code I've tried fails to run the function or redirect to new page, any help would be appreciated i tried using html tag and request.getContextPath but no avail... it returns 404 error or returns a blank page

Here is my servlet code

public class StudentServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private StudentDao studentDao;

    public StudentServlet() {
        this.studentDao = new StudentDao();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String sPath = request.getServletPath();
        //switch statement to call appropriate method
        switch (sPath) {
            case "/new":
                try {
                    showNewForm(request, response);
                } catch (ServletException | IOException e) {
                    e.printStackTrace();
                }
                break;
            case "/insert":
                try {
                    insertStudent(request, response);
                } catch (SQLException | IOException e) {
                    e.printStackTrace();
                } 
                break;
            case "/delete":
                try {
                    deleteStudent(request, response);
                } catch (SQLException | IOException e) {
                    e.printStackTrace();
                }
                break;
            case "/update":
                try {
                    updateStudent(request, response);
                } catch (SQLException | IOException e) {
                    e.printStackTrace();
                }
                break;
            case "/edit":
                try {
                    editStudent(request, response);
                } catch (ServletException | IOException e) {
                    e.printStackTrace();
                } 
            default:
                try {
                    listAllStudents(request, response);
                } catch (ServletException | IOException | SQLException e) {
                    e.printStackTrace();
                } 
                break; 
            } 
    }

    // functions to fetch data from studentDao and display data on appropriate jsp
    private void listAllStudents(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException, SQLException {
        List<Student> allStudents = studentDao.selectAllStudents();
        request.setAttribute("listStudents", allStudents);
        RequestDispatcher dispatch = request.getRequestDispatcher("student-list.jsp"); //home page week04/StudentServlet | list all objects from table
        dispatch.forward(request, response);
    }
    
    private void showNewForm(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
        RequestDispatcher dispatch = request.getRequestDispatcher("student-form.jsp");
        dispatch.forward(request, response);
    }

    private void insertStudent(HttpServletRequest request, HttpServletResponse response) 
            throws SQLException, IOException{
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        Student newStudent = new Student(name, email);
        studentDao.insertStudent(newStudent); //student object inserted to table 
        response.sendRedirect("listStudents"); //redirect to home page
    }
    
    private void deleteStudent(HttpServletRequest request, HttpServletResponse response) 
            throws SQLException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        studentDao.deleteStudent(id); //student object deleted
        response.sendRedirect("listStudents");
    }
    
    private void updateStudent(HttpServletRequest request, HttpServletResponse response) 
            throws SQLException, IOException{
        int id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        Student updateStudent = new Student(id, name, email);
        studentDao.updateStudent(updateStudent); //student object updated
        response.sendRedirect("listStudents");
    }
    
    private void editStudent(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Student currentStudent = studentDao.selectStudent(id);
        RequestDispatcher dispatch = request.getRequestDispatcher("student-form.jsp");
        request.setAttribute("student", currentStudent); //student object updated
        dispatch.forward(request, response);
    }

}

and here is my jsp page

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="java.util.*" import="week04.model.Student"%>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, intial-scale=1 shink-to-fit=yes">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" 
    integrity="sha384-... " crossorigin="anonymous">
</head>
<body>
    <div class="container-fluid">
    <nav class="navbar navbar-dark bg-primary pd-8">
        <a class="navbar-brand">XYZ University</a>
    </nav>
    <div class="container">

            <div class="container-fluid p-4">
               <a href="/new" class="btn btn-success" action="/new">Add
                    Student</a>
            </div>
            <br>
            
            <!--Assigning ArrayList object containing student data to the local object -->
            <% ArrayList<Student> studentList = (ArrayList) request.getAttribute("listStudents"); %> 
            <table class="table table-bordered">
            
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <%
                     if(request.getAttribute("listStudents") != null)  {
                            Iterator<Student> iterator = studentList.iterator();
                            while(iterator.hasNext()) {
                                Student studentDetails = iterator.next();
                    %>
                        <tr><td><%=studentDetails.getId()%></td>
                            <td><%=studentDetails.getName()%></td>
                            <td><%=studentDetails.getEmail()%></td>
                            <td><a href="<%=request.getContextPath()%>/update">Update</a>
                                &nbsp;&nbsp;&nbsp;&nbsp; <a href="<%=request.getContextPath()%>/delete">Delete</a></td>
                        </tr>
                    <% 
                            }
                     }
                    %>
                </tbody>
                
            </table>
            </div>
        </div>
         
    </body>
</html>

and here is my xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd http://java.sun.com/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee" id="WebApp_ID" version="2.4">
  
  <servlet>
    <description></description>
    <display-name>StudentServlet</display-name>
    <servlet-name>StudentServlet</servlet-name>
    <servlet-class>week04.web.StudentServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>StudentServlet</servlet-name>
    <url-pattern>/StudentServlet</url-pattern>
  </servlet-mapping>
</web-app>

Any help on what i'm doing wrong would be appreciated.


Solution

  • You need to tell the servlet in the web.xml that it processes the specified URLs.

      <servlet-mapping>
        <servlet-name>StudentServlet</servlet-name>
        <url-pattern>/StudentServlet</url-pattern>
        <url-pattern>/new</url-pattern>
      </servlet-mapping>
    

    Additionally, href must be specified correctly.

    <div class="container-fluid p-4">
        <a href="new" class="btn btn-success" action="/new">Add Student</a>
    </div>