The Java EE 5 Tutorial

Transferring Control to Another Web Component

In some applications, you might want to have one web component do preliminary processing of a request and have another component generate the response. For example, you might want to partially process a request and then transfer to another component depending on the nature of the request.

To transfer control to another web component, you invoke the forward method of a RequestDispatcher. When a request is forwarded, the request URL is set to the path of the forwarded page. The original URI and its constituent parts are saved as request attributes javax.servlet.forward.[request-uri|context-path|servlet-path|path-info|query-string]. The tut-install/javaeetutorial5/examples/web/bookstore2/src/java/com/sun/bookstore2/dispatcher/Dispatcher servlet, used by a version of the Duke’s Bookstore application described in The Example JSP Pages, saves the path information from the original URL, retrieves a RequestDispatcher from the request, and then forwards to the JSP page, tut-install/javaeetutorial5/examples/web/bookstore3/web/template/template.jsp.

public class Dispatcher extends HttpServlet {
    public void doGet(HttpServletRequest request,
         HttpServletResponse response) {
        RequestDispatcher dispatcher = request.
            getRequestDispatcher("/template.jsp");
        if (dispatcher != null)
            dispatcher.forward(request, response);
    }
    public void doPost(HttpServletRequest request,
     ...
}

The forward method should be used to give another resource responsibility for replying to the user. If you have already accessed a ServletOutputStream or PrintWriter object within the servlet, you cannot use this method; doing so throws an IllegalStateException.