For example, in our Confirm.jsp we may want to print out the User's first and last name.
The Controller can pass the Model to the View using request attributes.
Update your HelloWorld.java as shown below:
package org.confucius;
package org.confucius;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorld extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
User user = new User(request.getParameter("firstName"), request.getParameter("lastName"));
String view = null;
if (user.validate()){
view = "/jsp/Confirm.jsp";
}
else{
view = "/jsp/Error.jsp";
}
request.setAttribute("user", user);
getServletConfig().getServletContext().getRequestDispatcher(view).forward(request,response);
}
}
We are now passing the User by setting it as an attribute.
Update your Confirm.jsp as follows:
<html>
<head>
<%@ page import="org.confucius.User" %>
</head>
<body>
<% User user = (User) request.getAttribute("user"); %>
Confirmation: Registration accepted for <%out.println(user.getFirstName() + " " + user.getLastName());%>
</body>
</html>
Here we get the User from the attribute, and print out its first and last name.
If build and deploy HelloWorld.war, and point your browser to:
http://localhost:8080/HelloWorld/jsp/HelloWorld.jsp
you will be able to see the Users first and last name in the confirmation message.
No comments:
Post a Comment