Combining JSP and Servlets (2009-10-19)
Common approach:
- Servlets handle the contents (using lots of Java code)
- JSP pages handle the presentation (using lots of HTML)
- communicate using HttpSession attributes, forward requests using RequestDispatcher
Example Servlet receiving the original request:
public class Register extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
String email = request.getParameter("email");
HttpSession session = request.getSession(true);
session.setAttribute("email", email);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/present.jsp");
dispatcher.forward(request, response);
}
}
|
JSP page producing the final response:
mailing list
<h1>Welcome!</h1>
You have registered the following address:
<tt><%= session.getAttribute("email") %></tt>
<p><a href="continue">Continue</a>
</body></html>
|
- this quickly becomes a mess...
|