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.
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.
Delete the line of code in the doPost
method that prints the 'Hello World' message.
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.
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.
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");