Java Reference
In-Depth Information
Example 18−5: forcelogin.jsp
<%--forcelogin.jsp
This is a fragment of JSP code. It cannot stand alone, but is
intended to be included within other JSP pages. It looks for a
"username" attribute in the Session object, and if it does not find
one, it forwards the request to the login.jsp page, which will
authenticate the user and store their name in the session object.
This code sends a "nextpage" request parameter to the login.jsp, so
that the login page knows where to return to once the user has
successfully logged in. Note that request parameters passed to this
page are not preserved when the login page redirects back to this page.
--%>
<%
// Check whether the username is already defined in the Session object
String _username = (String) session.getAttribute("username");
if (_username == null) { // If the user has not already logged in
String _page = request.getRequestURI();
%>
<%-- Invoke the login.jsp page. The <jsp:forward> tag invokes the --%>
<%-- page directly on the server side without sending a redirect --%>
<%-- to the client The <jsp:param> tags specify request parameters --%>
<%-- that are passed to login.jsp --%>
<jsp:forward page='login.jsp'>
<jsp:param name='nextpage' value='<%=_page%>'/>
<jsp:param name='title'
value='<%= "You must log in to access " + _page%>'/>
</jsp:forward>
<%}%>
JSP Pages and JavaBeans
Example 18-6 is a listing of the JSP page portal.jsp . This example integrates many
of the servlets and servlet programming techniques demonstrated in this chapter to
create a very trivial Internet portal that displays customized content for its regis-
tered users. Figure 18-4 illustrates its output.
The major new feature of Example 18-6 is its use of a JavaBeans component (see
Example 18-7) to move functionality (and the Java code that implements it) out of
the JSP page into a separate Java class, thereby increasing the separation between
Java and HTML code. portal.jsp uses the <jsp:useBean> , <jsp:setProperty> , and
<jsp:getProperty> tags to instantiate and manipulate the bean. The <jsp:use-
Bean> tag instantiates the bean and assigns the instance a name; this name can be
used by the other JSP tags and by Java code in JSP expressions and scriptlets. The
scope="session" attribute specifies that the bean instance should be associated
with the user's session. In other words, the bean is instantiated when the user first
visits the page. At that time, it is stored in the session object, so it can be retrieved
on subsequent visits by that user during the same session.
The bean we create is an instance of UserBean , a simple class listed in Example
18-7. This class represents a single user of the portal and has methods for return-
ing information about the user, such as his favorite color, and a string of cus-
tomized HTML content that the portal should display.
Search WWH ::




Custom Search