Session State

Although Faces manages to obscure the fact that the framework is embedded in a Web/HTTP context most of the time, in the matter of maintaining state between user interactions one should probably be aware that the system is lodged within a JVM within a Web Container as opposed to some other context, such as a stand alone application or an Applet.  That is, one is likely to use an HTTPSession as the vehicle for maintaining state, which one is likely to associate with Servlets and other JavaServer components.  Of course, one could use URL rewriting or an external resource, such as a database or the file system, for maintaining state, but these approaches are likely to be less efficient and more elaborate than is justified in the kinds of applications being discussed in these lessons.  (If one were developing an application that was going to be deployed to multiple servers and if user interactions were to be distributed across multiple servers, then such approaches would be warranted.)

One other option that is available in Faces is to set the scope of ManagedBeans to session;  however, the consensus seems to be that it is far preferable to use scope request whenever possible.

Consequently, the approach shown here uses an HTTPSession instance just as was done in Struts and JSP implementations.  


Example

	
protected HttpSession getSession()  {
		
	FacesContext context = FacesContext.getCurrentInstance();
	HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
	HttpSession session = request.getSession( true );
		
	return session;

}

Comments

This "helper method" could, of course, be placed in any managed bean that needs to maintain or propagate state.  Since many applications will require state in most if not all of their managed beans, I elected to place the method in a superclass from which all managed beans are extended.  Hence the designation protected.  If the method were to appear in individual beans, then the proper designation would be private

In the individual beans, an HttpSession variable is declared globally, and the method is called  and the variable set in the constructor;  hence, the session object will be available through the bean.