joi, 10 decembrie 2015

JSF 2.3 Default Producer Example

As you probably know, JSF uses static entry methods and chaining to let the user obtain the various artifacts that it provides, such as the FacesContext, session map, external context, etc. But, this is pretty verbose and sometimes hard to intuit and understand. JSF 2.3 will therefore provide default producers for the most important artifacts. The entire list in available here.

In this post, you can see a simple example of injecting the request parameters map. So, let's have a simple Facelets:

<h:body>                   
 <h:form>                      
  <h:commandButton value="Hello World!" action="#{helloWorldBean.sayHello()}">                                   
   <f:param name="year" value="2016"/>
  </h:commandButton>
 </h:form>
</h:body>

Now, in the HelloWorldBean we inject the request parameters map and access the year request parameter:

import java.util.Map;
import javax.enterprise.context.RequestScoped;
import javax.faces.annotation.RequestParameterMap;
import javax.inject.Inject;
import javax.inject.Named;

@Named
@RequestScoped
public class HelloWorldBean {

 @Inject
 @RequestParameterMap
 private Map<String, String> requestMap;

 public void sayHello() {
  System.out.println("Hello World in " + requestMap.get("year"));
 }
}

Output in console will be:
Hello World in 2016

Note In order to activate the CDI EL resolving and injection (for now) the context parameter javax.faces.ENABLE_CDI_RESOLVER_CHAIN needs to be set to true (otherwise EL resolving will use the old (JSF native) implicit object resolver, and injection will not work (throws exception)):

<context-param>
 <param-name>javax.faces.ENABLE_CDI_RESOLVER_CHAIN</param-name>
 <param-value>true</param-value>
</context-param>

The complete application is available here.

Special thanks to Arjan Tijms for contributing to this post.

2 comentarii: