Almost every JSF application that I am aware of uses some mechanism to store values in a scope longer than the original “Request Scope” but shorter than “Session Scope”. “Wizards” are a common scenario. Unfortunately, JSF comes without something like a conversation scope, but there are some frameworks that offer this functionality:

MyFaces Orchestra

Seam

Spring

CDI

So, while technical solutions exist, they require integration of at least one 3rd party library. Not a big deal in a newly created project, but it can become a serious problem with existing code or legacy applications.

JSF 2.2 addresses this problem with a cool new feature: “Flow scopes” (See this excellent post about whats hot in JSF 2.2). While it might be a nice solution, it is still unclear to me if “Flow Scopes” will work without CDI. Besides this, JSF 2.2 Flows seem to require a lot of configuration so it might be somewhat oversized and less suitable in some scenarios.

Though JSF lacks a “conversation scope” and JSF 2.2 is still not yet available, there is already a JSF 2.0 feature that seems to be mostly unknown to a lot of JSF developers: JSF “Custom Scopes”.

Custom scopes were anounced as a major feature for JSF 2 (see this blogpost from Andy Schwartz) but for some reason it must have fallen from grace: The final release of the JSF 2 specification remains silent on custom scopes, though the API includes the necessary annotation and events .

While I think custom scopes are an enormous useful feature, there are very few resources dealing with it. There is an older blog post from Ryan Lubke which uses an outdatet API (early draft I guess).

So, if f you need a custom scope, here is how to create one:

First of all, we need a class that will represent our custom scope. This class will be responsible for storing named objects. Stored objects will be accessible using EL expressions. So, insted of putting our managed beans into request scope, we will be able to put them into our custom scope. The class therefore needs to implement the map interface:

public class CustomScope extends ConcurrentHashMap<string, Object> { private static final long serialVersionUID = 6013804747421198557L; public static final String SCOPE_NAME = "CUSTOM_SCOPE"; public CustomScope(){ super(); } public void notifyCreate(final FacesContext ctx) { ScopeContext context = new ScopeContext(SCOPE_NAME, this); ctx.getApplication().publishEvent(ctx, PostConstructCustomScopeEvent.class, context); } public void notifyDestroy(final FacesContext ctx) { ScopeContext scopeContext = new ScopeContext(SCOPE_NAME,this); ctx.getApplication().publishEvent(ctx, PreDestroyCustomScopeEvent.class, scopeContext); } }

The scope itself needs to be held somewhere. For this example it will be put into session scope for the time needed. At a particular point in time we can discard the scope by removing it from session.

So, whats the point of having a custom scope when it will be stored in session anyway?

The scope can contain many beans that we would else have to put in (and remove from) the session manually. We can also remove them all at once by removing the scope object from session. This way, the risk to forget to clean things up is greatly reduced.

Defining beans to belong to our custom scope is not only convenient, it also enables us to have distinct scopes for different aspects of the application. All session data may be accessed concurrently (multiple browser windows). This is why the scope class needs to extend java.util.concurrent.ConcurrentHashMap. The class furthermore provides two methods to publish SystemEvents, so other components may be notified when the scope is created or destroyed.

This is how a managed bean can be attached to our custom scope:

@ManagedBean @CustomScoped("#{customScope}") public class ExampleBean implements Serializable { ... }

As you can see, the name of the scope has to be defined in the annotations EL expression.

For JSF to be able to resolve the EL expression, we need to define a custom ELResolver. ELResolvers do axactly that: They try to resolve EL expressions. You can have any number of ELResolvers in your application. They are chained together in the order of their occurence in the faces-config.xml. This is the code for the ELResolver for our custom scope:

public class CustomScopeELResolver extends ELResolver { @Override public Object getValue(final ELContext elContext, final Object base, final Object property) { if (property == null) { throw new PropertyNotFoundException(); } FacesContext facesContext = (FacesContext) elContext.getContext(FacesContext.class); if ((null == base) && CustomScope.SCOPE_NAME.equals(property.toString())) { // Scope is referenced directly CustomScope scope = getScope(facesContext); elContext.setPropertyResolved(true); return scope; } else if ((null != base) && (base instanceof CustomScope)) { // An object within the scope is referenced return resolve(facesContext, (CustomScope) base, property.toString()); } else if (null == base) { CustomScope customScope = getScope(facesContext); return null != customScope ? resolve(facesContext, customScope, property.toString()):null; } return null; } /** * Resolve the key on the given CustomScope */ public Object resolve(final FacesContext facesContext, final CustomScope scope, final String key) { Object value = scope.get(key); facesContext.getELContext().setPropertyResolved(value != null); return value; } /** * Responsible to retrieve the scope */ private CustomScope getScope(final FacesContext facesContext) { Map<string, Object> sessionMap = facesContext.getExternalContext().getSessionMap(); CustomScope customScope = (CustomScope) sessionMap.get(CustomScope.SCOPE_NAME); return customScope; } ... }

The ELResolver needs to be defined in faces-config.xml:

<?xml version="1.0" encoding="UTF-8"?> <faces-config version="2.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"> <application> <el-resolver>de.thomasasel.jsf.example.CustomScopeELResolver</el-resolver> </application> </faces-config>

The getValue-Method will be called once an ELExpression needs to be resolved. The resolver will return null if the expression cannot be resolved.

In this case the next resolver in the chain will be called and so on until the expression is either finally resolved or the last ELResolver returns null.

By now we have a managed bean that is tied to the custom scope. Thanks to our custom EL resolver we can access the bean and its properties from markup using EL:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <h:head> <title>Custom Scope example</title> </h:head> <h:body> <h:form> <h:inputText value="#{exampleBean.text1}"/> </h:form> </h:body> </html>

As you can see, the bean is referenced by name as it would be the case with any other scope.

Finally we need to control the lifecycle of the scope. When will it be created? When is it destroyed?

I decided to use ActionListeners for this task. The listeners will put the custom scope in the session and remove it from there. They will also notify other components by calling the scopes notifyCreate and notifyDestroy methods:

public class CreateCustomScope implements ActionListener { @Override public void processAction(final ActionEvent event) throws AbortProcessingException { FacesContext facesContext = FacesContext.getCurrentInstance(); Map<string, Object> sessionMap = facesContext.getExternalContext().getSessionMap(); CustomScope customScope = new CustomScope(); sessionMap.put(CustomScope.SCOPE_NAME, customScope); customScope.notifyCreate(facesContext); } } public class DestroyCustomScope implements ActionListener { @Override public void processAction(final ActionEvent event) throws AbortProcessingException { FacesContext facesContext = FacesContext.getCurrentInstance(); Map<string, Object> sessionMap = facesContext.getExternalContext().getSessionMap(); CustomScope customScope = (CustomScope) sessionMap.get(CustomScope.SCOPE_NAME); customScope.notifyDestroy(facesContext); sessionMap.remove(CustomScope.SCOPE_NAME); } }

Both listeners are attached to some navigations buttons, so the lifecycle of the scope depends on the users navigation path.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <h:head> <title>Custom Scope example</title> </h:head> <h:body> <h:form> <h:commandButton value="start" action="page1.xhtml"> <f:actionListener type="de.thomasasel.jsf.example.CreateCustomScope" /> </h:commandButton> </h:form> </h:body> </html>

ActionListeners were chosen just for the sake of simplicity for this example. A custom NavigationHandler using JSFs ConfigurableNavigationHandler API is a way more flexible and clean solution as it keeps the aspect of lifecycle control out of the view declaration.

Thats it. Nothing left to do but to play around with this cool feature. You can get the sourcecode for this example from GitHub

If anybody has information about why CustomScopes are not mentioned with a single word in the spec, please drop me a line.

0 0

Like this: Like Loading...

Related