15.7 Forwarding Requests from JSP Pages

15.7 Forwarding Requests from JSP Pages

The most common request-forwarding scenario is one in which the request first goes to a servlet and the servlet forwards the request to a JSP page. The reason a servlet usually handles the original request is that checking request parameters and setting up beans requires a lot of programming, and it is more convenient to do this programming in a servlet than in a JSP document. The reason that the destination page is usually a JSP document is that JSP simplifies the process of creating the HTML content.

However, just because this is the usual approach doesn't mean that it is the only way of doing things. It is certainly possible for the destination page to be a servlet. Similarly, it is quite possible for a JSP page to forward requests elsewhere. For example, a request might go to a JSP page that normally presents results of a certain type and that forwards the request elsewhere only when it receives unexpected values.

Sending requests to servlets instead of JSP pages requires no changes whatsoever in the use of the RequestDispatcher . However, there is special syntactic support for forwarding requests from JSP pages. In JSP, the jsp:forward action is simpler and easier to use than wrapping RequestDispatcher code in a scriptlet. This action takes the following form:

 <jsp:forward page="Relative URL" /> 

The page attribute is allowed to contain JSP expressions so that the destination can be computed at request time. For example, the following code sends about half the visitors to http:// host /examples/page1.jsp and the others to http:// host /examples/page2.jsp .

 <% String destination;    if (Math.random() > 0.5) {      destination = "/examples/page1.jsp";    } else {      destination = "/examples/page2.jsp";    } %> <jsp:forward page="<%= destination %>" /> 

The jsp:forward action, like jsp:include , can make use of jsp:param elements to supply extra request parameters to the destination page. For details, see the discussion of jsp:include in Section 13.2.

Core Servlets and JavaServer Pages (Vol. 1.Core Technologies)
Core Servlets and Javaserver Pages: Core Technologies, Vol. 1 (2nd Edition)
ISBN: 0130092290
EAN: 2147483647
Year: 2002
Pages: 194

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net