Core Servlets and Javaserver Pages: Core Technologies, Vol. 1 (2nd Edition)

You use jsp:include to combine output from the main page and the auxiliary page. Instead, you can use jsp:forward to obtain the complete output from the auxiliary page. For example, here is a page that randomly selects either page1.jsp or page2.jsp to output.

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

To use jsp:forward , the main page must not have any output. This brings up the question, what benefit does JSP provide, then? The answer is, none! In fact, use of JSP is a hindrance in this type of situation because a real situation would be more complex, and complex code is easier to develop and test in a servlet than it is in a JSP page. We recommend that you completely avoid the use of jsp:forward . If you want to perform a task similar to this example, use a servlet and have it call the forward method of RequestDispatcher . See Chapter 15 for details.

Категории