Session Management in JSP
 
Request Chaining
 
Request chaining is a powerful feature and can be used to effectively meld JSP pages and servlets in processing HTML forms, as shown in the following figure:
 
 
Consider the following JSP page, say Bean1.jsp, which creates a named instance fBean of type FormBean, places it in the request, and forwards the call to the servlet JSP2Servlet.
Observe the way the bean is instantiated--here we automatically call the bean's setter methods for properties which match the names of the posted form elements, while passing the corresponding values to the methods.
<jsp:useBean id="fBean" class="govi.FormBean"
scope="request"/>
<jsp:setProperty name="fBean" property="*" />
<jsp:forward page="/servlet/JSP2Servlet" />
 
The servlet JSP2Servlet now extracts the bean passed to it from the request, makes changes using the appropriate setters, and forwards the call to another JSP page Bean2.jsp using a request dispatcher. Note that this servlet, acting as a controller, can also place additional beans if necessary, within the request.
public void doPost (HttpServletRequest request, HttpServletResponse response)
{
try
{
FormBean f = (FormBean) request.getAttribute ("fBean");
f.setName("Aman");
// do whatever else necessary
getServletConfig().getServletContext().
getRequestDispatcher("/jsp/Bean2.jsp").
forward(request, response);
}
catch (Exception ex)
{
. . .
}
}
 
The JSP page Bean2.jsp can now extract the bean fBean (and whatever other beans that may have been passed by the controller servlet) from the request and extract its properties.
<html>
<body>
<jsp:useBean id="fBean" class="govi.FormBean"
scope="request"/>
<jsp:getProperty name="fBean" property="name" />
</body>
</html>