Newer
Older
labs / tiddlers / content / labs / lab04 / _Labs_04_Adding a Student (Servlet).md
  1. Take a quick look at the code for the form again. Note the action and method attributes of the <form> tag.

    When the form is submitted, a POST request is going to be sent to the add-student path of the web application. This is the path that the AddNewStudent servlet is attached to.

  2. The servlet is currently only handling GET requests. Change the name of the doGet method to doPost so that the servlet will handle POST requests.

  3. Delete the line of code in the doPost method that prints the 'Hello World' message.

  4. We need somewhere to store the students as they are entered. Eventually we would expect the student data to be stored in a database, but for the purposes of this lab we will be storing the students in an ArrayList that is itself stored in the user's session. Add the following code to the doPost method:

     // get the user's session
     HttpSession session = req.getSession();
    
     // get the studentList from the session
     Collection<Student> students = (Collection<Student>) session.getAttribute("studentList");
    
     // if the studentList has not yet been added to the session then add it
     if (students == null) {
         students = new ArrayList();
         session.setAttribute("studentList", students);
     }

    The comments describe what is happening here.

  5. Add the following code to the doPost method below the previous code to extract the form data and create a Student domain object:

    // extract the form data
    String id = req.getParameter("id");
    String name = req.getParameter("name");
    String address = req.getParameter("address");
    
    // create the student object
    Student student = new Student(id, name, address);
    
    // add the student to the list
    students.add(student);

    The id, name, and address parameters are the ones declared in the name attributes of the form componets in the add-student.html page.

  6. The final step is to redirect the web browser to the next page. We will redirect the browser back to the index/menu page. Add the following line below to the bottom of the doPost method:

     resp.sendRedirect("index.html");