Java Reference
In-Depth Information
Example 18−6: portal.jsp (continued)
</jsp:include>
times. The portal has been visited
<jsp:include page='portal.jsp.count' flush='true'/>
times.
</decor:box>
</td></tr></table>
</decor:box>
Example 18-7 is a listing of UserBean.java , the JavaBeans class used by portal.jsp .
It is a standard Java class, with getter and setter methods that follow the JavaBeans
naming conventions. Note that the getCustomContent() method has a particularly
unambitious implementation: a real web portal application would have to provide
much more meaningful content than this method does.
One interesting feature of the UserBean class is that it implements HttpSession-
BindingListener . This means that its valueBound() method is called when an
instance is stored in a servlet's HttpSession object, and its valueUnbound()
method is called when an instance is removed from the session. In the example,
UserBean is removed from the session only when the session itself is being
destroyed, either because the user logged out, the user became inactive, or
because the server itself is shutting down. In any of these cases, the valueUn-
bound() method provides an opportunity for the bean to save its state to some
kind of persistent storage, from which it can be restored by the setUserName()
method. The valueUnbound() and setUserName() of this class do not currently
save and restore state, but in a robust implementation they would.
Example 18−7: UserBean.java
package com.davidflanagan.examples.servlet;
import javax.servlet.http.*;
/**
* This class is a simple non-visual JavaBean that defines properties that can
* be used from a JSP page with the <jsp:useBean>, <jsp:setProperty> and
* <jsp:getProperty> tags. These JSP tags allow significant chunks of Java
* code to be taken out of JSP pages and placed in Java files, where they are
* easier to read, edit, and maintain. This example only defines a few
* trivial properties, but the class could do much more.
*
* This class is instantiated by portal.jsp and is bound in the Session object.
* Therefore, it implements HttpSessionBindingListener so that it is notified
* when the session is terminated (when the user logs out or the session
* times out).
**/
public class UserBean implements HttpSessionBindingListener {
String username; // The name of the user we represent
String favorite = colors[0]; // The user's favorite color, with a default
static final String[] colors = { "gray", "lightblue", "pink", "yellow" };
// These are the getter and setter methods for the userName property
// In a real program, setUserName() would probably look up information
// about the user in a database of some kind.
public String getUserName() { return username; }
public void setUserName(String username) { this.username = username; }
// These are the getter and setter methods for the favoriteColor property
Search WWH ::




Custom Search