Show me an example of POST request chaining using JSPs and servlets.

Govind Seshadri

[See also http://www.jguru.com/jguru/faq/view.jsp?EID=231318]

The following code example demonstrates how request chaining can be implemented using a combination of JSPs and servlets.

Consider the following JSP page, say Bean1.jsp, which essentially instantiates the bean fBean, 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 corrosponding 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"); 
    // do whatever else necessary
             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.

Within JSP2

<jsp:useBean id="fBean" class="govi.FormBean" scope="request"/> <jsp:getProperty name="fBean" property="name" /> </body> </html>