Java Reference
In-Depth Information
succeeds. login.jsp stores the user's login name in the session object under the
name username , which is exactly where the Hello servlet looks for it. Thus, you
can use these servlets together with a URL like this:
http://localhost:8080/javaexamples2/login.jsp?nextpage=servlet/hello
Doing so obtains a username for the Hello servlet, but it does not provide any
actual access control; the user can run Hello directly with a /servlet/hello URL. In
the next section, we'll see a technique that does require login.
Request Forwarding
Near the end of Example 18-3, we saw an example of using the RequestDis-
patcher class to include the output of one servlet within the output of another. In
addition to its include() method, the RequestDispatcher class also has a for-
ward() method, which transfers, or forwards, a request from one servlet to
another. When this method is called, processing of the first servlet ends, and the
second servlet takes over the job of producing output for the user. The only
restriction on servlet forwarding is that the first servlet must not have already
begun to produce output. A servlet that may forward to another servlet typically
buffers its output in case it ends up having to forward to another page. JSP pages
perform buffering automatically and allow a buffer size to be declared with the
@page directive.
JSP provides an interface to the RequestDispatcher class through two custom tags
that are part of the default JSP tag library. (This tag library is always available with
the prefix jsp: ; it does not need to be declared with a @taglib directive.) The
<jsp:include> tag performs servlet (or JSP page) inclusion, and the <jsp:for-
ward> tag does forwarding. Example 18-5 is a listing of forcelogin.jsp , which is a
JSP page fragment that demonstrates the use of the <jsp:forward> tag.
forcelogin.jsp is not a complete JSP page; it is a page fragment that is intended to
be statically included into another JSP page using an @include directive:
<%@include file="forcelogin.jsp"%>
It is important to understand that the @include directive performs static, compile-
time file inclusion, rather than the dynamic, request-time inclusion performed by
the <jsp:include> tag. Example 18-6 includes forcelogin.jsp with an @include
directive in exactly this way.
The code in forcelogin.jsp checks to see if the session object has a username
attribute defined. If not, it concludes that the user has not logged in and uses a
<jsp:forward> tag to forward the user's request to the login.jsp page we saw in
Example 18-4. It also uses a <jsp:param> tag to set the nextpage request parame-
ter to tell login.jsp what page to come back to when the login is complete. Finally,
because forcelogin.jsp is not a standalone JSP page, it does not have a URL of its
own, so it uses the getRequestURI() method to figure out the URL for the page in
which it has been included.
Search WWH ::




Custom Search