to the main page about the tutorial  INTERACTIVE WEB SERVICES WITH JAVA back up next

Combining JSP and Servlets

Common approach: - 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:
<html><head>mailing list</head><body>
<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...

Often, applications are composed of JavaBean Components.

back COPYRIGHT © 2002-2003 ANDERS MØLLER & MICHAEL I. SCHWARTZBACH next