Java Reference
In-Depth Information
Example 18−7: UserBean.java (continued)
public String getFavoriteColor() { return favorite; }
public void setFavoriteColor(String favorite) { this.favorite = favorite; }
// Return a list of colors the user is allowed to choose from
public String[] getColorChoices() { return colors; }
// This is a getter method for the "customContent" property. In a more
// sophisticated example, this method might query a database and return
// current news clippings or stock quotes for the user. Not here, though.
public String getCustomContent() {
return "Your name backwards is: <tt>" +
new StringBuffer(username).reverse() + "</tt>";
}
// This method implements HttpSessionBindingListener. If an instance of
// this class is bound in a HttpSession object, then this method will
// be invoked when the instance becomes unbound, which typically happens
// when the session is invalidated because the user logged out or
// was inactive for too long. In a real example, this method would
// probably save information about the user to a file or database.
public void valueUnbound(HttpSessionBindingEvent e) {
System.out.println(username + " logged out or timed out." +
" Favorite color: " + favorite);
}
// Part of HttpSessionBindingListener; we don't care about it here
public void valueBound(HttpSessionBindingEvent e) {}
}
Ending a User Session
The portal example (Example 18-6) requires the user to log in the first time he vis-
its and provides a Logout button that enables the user to log out. These login and
logout events correspond to the creation and destruction of a javax.servlet.
http.HttpSession object that maintains state for a single user of the web applica-
tion. The HTTP protocol (the protocol of the Web) is a stateless protocol: every
HTTP request is independent from every other one, and web servers do not main-
tain any state between requests. Because of the fundamentally stateless nature of
the underlying protocol, one useful feature of servlet containers is that they per-
form session tracking, usually by placing a transient (and benign) cookie in the
client's browser. The cookie contains a unique identifier the servlet container uses
to identify the session. *
Sessions do not last forever: if a user does not issue a request to the web applica-
tion within a specified session timeout period, the servlet container ends the ses-
sion. The session timeout interval is one of the many configuration options that
can be specified in the WEB-INF/web.xml deployment file (see Example 18-11).
* Session tracking can also be done if the end user has disabled cookies, with a technique called URL
rewriting, in which the unique session identifier is added as a request parameter to all URLs in the web
application. URLs are rewritten with the encodeURL() and encodeRedirectURL() methods of Http-
ServletResponse .
Search WWH ::




Custom Search