Home > Back-end >  Restart Servlet after form submit
Restart Servlet after form submit

Time:09-17

I'm fairly new to using servlets with JSP and I am having trouble trying to redirect back to the start of the servlet home page JSP after submitting my form jsp and I'm not sure how to accomplish this task or whether it's even possible to do that, the methods i try have at best returned the home page jsp but without the servlet default function called to fetch the data from jdbc. i've tried sendredirect() and request dispatcher to no avail and any help to where i'm going wrong would be appreciated.

i have one single servlet code for handling all operations including the insert and update which are giving problems in redirecting/reloading

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();
                }
                break;
            case "/StudentServlet":
                try {
                    listAllStudents(request, response); 
                } catch (ServletException | IOException | SQLException e) {
                    e.printStackTrace();
                } 
                break;
            default:
                try {
                    listAllStudents(request, response); //home page = .../week04/StudentServlet
                } 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"); 
        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 firstname = request.getParameter("firstname");
        String lastname = request.getParameter("lastname");
        String email = request.getParameter("email");
        Student newStudent = new Student(firstname, lastname, email);
        studentDao.insertStudent(newStudent); //student object inserted to table 
        response.sendRedirect("/StudentServlet"); //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("/StudentServlet");
    }
    
    private void updateStudent(HttpServletRequest request, HttpServletResponse response) 
            throws SQLException, IOException{
        String sId = request.getParameter("id");
        int id = Integer.parseInt(sId);
        String firstname = request.getParameter("firstname");
        String lastname = request.getParameter("lastname");
        String email = request.getParameter("email");
        Student updateStudent = new Student(id, firstname, lastname, email);
        studentDao.updateStudent(updateStudent); //student object updated
        response.sendRedirect("/StudentServlet");
    }
    
    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"); //student form called with current student info loaded
        request.setAttribute("student", currentStudent); 
        dispatch.forward(request, response);
    }
    
}

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>
    <servlet-name>StudentServlet</servlet-name>
    <servlet-class>week04.web.StudentServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>StudentServlet</servlet-name>
    <url-pattern>/</url-pattern>
    <url-pattern>/StudentServlet</url-pattern>
    <url-pattern>/new</url-pattern>
    <url-pattern>/update</url-pattern>
    <url-pattern>/insert</url-pattern>
    <url-pattern>/delete</url-pattern>
    <url-pattern>/edit</url-pattern>
  </servlet-mapping>
</web-app>

here is my home page JSP i named it student-list.jsp

<%@ 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="sha38-...." crossorigin="anonymous">
</head>
<body>
    <nav class="navbar navbar-dark bg-primary pd-8">
         <a class="navbar-brand">&nbsp;&nbsp;&nbsp;&nbsp;XYZ University</a>
    </nav>
    <div class="container-fluid">
    <div class="container">

            <div class="form container-fluid p-4">
               <a href="<%=request.getContextPath()%>/new" class="btn btn-success" >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>First Name</th>
                        <th>Last 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.getFirstname()%></td>
                            <td><%=studentDetails.getLastname()%></td>
                            <td><%=studentDetails.getEmail()%></td>
                            <td><a href="<%=request.getContextPath()%>/edit?id=<%=studentDetails.getId()%>">Update</a>
                                &nbsp;&nbsp;&nbsp;&nbsp; <a href="<%=request.getContextPath()%>/delete?id=<%=studentDetails.getId()%>">Delete</a></td>
                        </tr>
                    <% 
                            }
                     }
                    %>
                </tbody>
                
            </table>
            </div>
        </div>
         
    </body>
</html>

and here is my form file that handles inserting and updating data:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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-...">
</head>
<body>
    <nav class="navbar navbar-dark bg-primary pd-8">
         <a class="navbar-brand">&nbsp;&nbsp;&nbsp;&nbsp;XYZ University</a>
    </nav>
    <div class="container col-md-5 p-4">
        <div class="card">
            <div class="card-body">
        <% System.out.println(request.getAttribute("student")   "hello"); %>
                <% if (request.getAttribute("listStudents") != null || request.getAttribute("student") != null) { %>
                    <form action="<%=request.getContextPath()%>/update" method="post">
                    <% } else { %>
                    <form action="<%=request.getContextPath()%>/insert" method="post">
                    <% } %>
    
                    <div>
                        <h2>
                        <% if (request.getAttribute("student") != null) { %>
                            Edit Student
                        <% } else { %>
                            Add New Student
                        <% } %>
                        </h2>
                    </div>

                <% if (request.getAttribute("student") != null) { %>
                    <input type="hidden" name="id" value="${student.id}" />
                <% } %>

                <fieldset class="form-group">
                    <legend> First Name</legend>
                    <% if (request.getAttribute("student") != null) { %>
                       <input type="text" value="${student.firstname}" class="form-control" 
                       name="fistname" required="required">
                    <% }  else { %>
                        <input type="text" value="" class="form-control" name="firstname" required="required">
                    <% } %>
                </fieldset>
                
                <fieldset class="form-group">
                    <legend>Last Name</legend>
                    <% if (request.getAttribute("student") != null) { %>
                       <input type="text" value="${student.lastname}" class="form-control" 
                       name="lastname" required="required">
                    <% }  else { %>
                        <input type="text" value="" class="form-control" name="lastname" required="required">
                    <% } %>
                </fieldset>

                <fieldset class="form-group">
                <legend>Email</legend>
                <% if (request.getAttribute("student") != null) { %>
                    <input type="text" value="${student.email}" class="form-control" name="email">
                <% }  else { %>
                    <input type="text" value="" class="form-control" name="email">
                <% } %>     
                </fieldset>
                
                <button type="submit" class="t-3 btn btn-success">Save</button>
                </form>
            </div>
        </div>
    </div>
    
</body>
</html>

Any help would be appreciated, i dont know if i'm going wrong with my servlet configuration, xml or my form page configuration.

CodePudding user response:

You're receiving the exception

SQLIntergrityConstraintViolation: column firstname cannot be null

because you have a small typo in your first name form group.

<% if (request.getAttribute("student") != null) { %>
   <input type="text" value="${student.firstname}" class="form-control" 
    name="fistname" required="required">
<% }  else { %>
    <input type="text" value="" class="form-control" name="firstname" required="required">
<% } %>

In the if block, the <input> text field's name="fistname" has been misspelled, while the name="firstname" is correct in the else block.

This is why your insert works with if-else only as it goes through the else block which has the correct field name. Once you fix this typo, the insert should start working without the if-else too as prescribed before.

  • Related