跳至主要内容

Activating CDI in JSF 2.3

Activating CDI in JSF 2.3

When I upgraded my Java EE 7 sample to the newest Java EE 8, the first thing confused me is the CDI beans are not recoganized in Facelects template in a JSF 2.3 based web applicaiton, which is working in the development version, but in the final release version, they are always resolved as null. I filed an issue on Mojarra and discussed it with the developers from communities and the JSF experts.
According to the content of README, In a JSF 2.3 application, to activate CDI support, declaring a 2.3 versioned faces-config.xml and adding javax.faces.ENABLE_CDI_RESOLVER_CHAIN in web.xml is not enough, you have to declare @FacesConfig annotated class to enable CDI.
Here is the steps I created a workable JSF 2.3 applicatoin in Java EE 8.
  1. Create a Java web application, this can be done easily by NetBeans IDE, or generated by Maven archetype, for exmaple.
    $ mvn archetype:generate -DgroupId=com.example
    -DartifactId=demo
    -DarchetypeArtifactId=maven-archetype-webapp
    -DinteractiveMode=false 
    
  2. Add javaee-api in project dependencies.
    <properties>
      <version.javaee-api>8.0</version.javaee-api>
      ...// other properties
    </properties>
    <dependencyManagement>
      <dependencies>
       <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>${version.javaee-api}</version>
        <scope>provided</scope>
       </dependency>
       ...//other dependencies
       </dependencies>  
    </dependencyManagement>
    <dependencies>
       <dependency>
       <groupId>javax</groupId>
       <artifactId>javaee-api</artifactId>
       </dependency>
       ...//other dependencies
    </dependencies>
  3. Add a faces-config.xml into WEB-INF folder, it is optional in JSF 2.3. ​
    <?xml version='1.0' encoding='UTF-8'?>
    <faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_3.xsd"
       version="2.3">
    </faces-config>
  4. Declare a beans.xml, CDI is enabled by default in Java EE 7, so it is optional.
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
        bean-discovery-mode="all" 
        version="2.0">
    </beans>
  5. Add web.xml. It is not required by JSF, but you can customize the application by some properties.
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
       version="4.0">
     <context-param>
      <param-name>javax.faces.FACELETS_REFRESH_PERIOD</param-name>
      <param-value>0</param-value>
     </context-param>
    
     <context-param>
      <param-name>javax.faces.PROJECT_STAGE</param-name>
      <param-value>Development</param-value>
     </context-param>
    
     <context-param>
      <param-name>javax.faces.validator.ENABLE_VALIDATE_WHOLE_BEAN</param-name>
      <param-value>true</param-value>
     </context-param>
    
     <context-param>
      <param-name>javax.faces.ENABLE_WEBSOCKET_ENDPOINT</param-name>
      <param-value>true</param-value>
     </context-param> 
    
     <!--    <context-param>
      <param-name>javax.faces.DISABLE_FACESSERVLET_TO_XHTML</param-name>
      <param-value>true</param-name>
     </context-param>-->
    </web-app>
    JSF 2.3 provides some options to activate the new features added in 2.3.
    • ENABLE_VALIDATE_WHOLE_BEAN is used to enable class level Bean validation
    • ENABLE_WEBSOCKET_ENDPOINT is used to enable websocket support
    • DISABLE_FACESSERVLET_TO_XHTML will disable JSF servelt mapping to *.xhtml. By default, JSF Servlet will serve *.xhtml.
  6. Declare a @FacesConfig annotated class to activate CDI in JSF 2.3.
    @FacesConfig(
    // Activates CDI build-in beans
    version = JSF_2_3 
    )
    public class ConfigurationBean {
    
    }
    Open the source code of FacesConfig, you will know it is a standard CDI Qualifier.
    @Qualifier
    @Target(TYPE)
    @Retention(RUNTIME)
    public @interface FacesConfig {
    
     public static enum Version {
    
      /**
       * <p class="changed_added_2_3">This value indicates CDI should be used
       * for EL resolution as well as enabling JSF CDI injection, as specified
       * in Section 5.6.3 "CDI for EL Resolution" and Section 5.9 "CDI Integration".</p>
       */
      JSF_2_3
    
     }
    
     /**
      * <p class="changed_added_2_3">The value of this attribute indicates that
      * features corresponding to this version must be enabled for this application.</p>
      * @return the spec version for which the features must be enabled.
      */
     @Nonbinding Version version() default Version.JSF_2_3;
    
    }
Done.
Another issue about JSF 2.3 still confused me and other developers, as the codes shown above, we use all bean-discovery-mode in the beans.xml. If we switch to annotated here, we have to add @FacesConfig to every CDI backing beans, it is unreasonable.
Create a simple sample to verify if it works.
Firstly create a simple backing bean to say hello to JSF.
@Named
@RequestScoped
public class HelloBean {

    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void sayHi() {
        this.message = this.message+ " received at " + LocalDateTime.now();
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 13 * hash + Objects.hashCode(this.message);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final HelloBean other = (HelloBean) obj;
        if (!Objects.equals(this.message, other.message)) {
            return false;
        }
        return true;
    }

}
And template will accept user input and show the message.
<!DOCTYPE html>
<html lang="en"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:jsf="http://xmlns.jcp.org/jsf">
    <h:head/>

    <h:messages />

    <h:body>
        <p>
            Hello JSF 2.3 with CDI activation
        </p>

        <form jsf:id="form">
            <p>
                <strong>Welcome to JSF 2.3 world: </strong> 
                <div>#{helloBean.message}</div>
            </p>
            <p>
                <strong>Message: </strong> 
                <div><input type="text" jsf:id="message" jsf:value="#{helloBean.message}"></input></div>
            </p>
            <p>
                <input type="submit" value="Say Hi to JSF" jsf:action="#{helloBean.sayHi()}" />
            </p>
        </form>

    </h:body>

</html>
Grab the source codes from my github account.

评论

meenati说…
I like your blog, I read this blog please update more content on hacking,Nice post
Angularjs Online Training
Carlos说…
Thank you for showing us how to enable cdi in JSF. I have been searching everywhere for a solution on how to enable cdi in jsf 2.3. Thank you.

此博客中的热门博文

Create a restful application with AngularJS and Zend 2 framework

Create a restful application with AngularJS and Zend 2 framework This example application uses AngularJS/Bootstrap as frontend and Zend2 Framework as REST API producer. The backend code This backend code reuses the database scheme and codes of the official Zend Tutorial, and REST API support is also from the Zend community. Getting Started with Zend Framework 2 Getting Started with REST and Zend Framework 2 Zend2 provides a   AbstractRestfulController   for RESR API producing. class AlbumController extends AbstractRestfulController { public function getList() { $results = $this->getAlbumTable()->fetchAll(); $data = array(); foreach ($results as $result) { $data[] = $result; } return new JsonModel(array( 'data' => $data) ); } public function get($id) { $album = $this->getAlbumTable()->getAlbum($id); return new JsonModel(array("data" =>

JPA 2.1: Attribute Converter

JPA 2.1: Attribute Converter If you are using Hibernate, and want a customized type is supported in your Entity class, you could have to write a custom Hibernate Type. JPA 2.1 brings a new feature named attribute converter, which can help you convert your custom class type to JPA supported type. Create an Entity Reuse the   Post   entity class as example. @Entity @Table(name="POSTS") public class Post implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Long id; @Column(name="TITLE") private String title; @Column(name="BODY") private String body; @Temporal(javax.persistence.TemporalType.DATE) @Column(name="CREATED") private Date created; @Column(name="TAGS") private List<String> tags=new ArrayList<>(); } Create an attribute convert

Auditing with Hibernate Envers

Auditing with Hibernate Envers The approaches provided in JPA lifecyle hook and Spring Data auditing only track the creation and last modification info of an Entity, but all the modification history are not tracked. Hibernate Envers fills the blank table. Since Hibernate 3.5, Envers is part of Hibernate core project. Configuration Configure Hibernate Envers in your project is very simple, just need to add   hibernate-envers   as project dependency. <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-envers</artifactId> </dependency> Done. No need extra Event listeners configuration as the early version. Basic Usage Hibernate Envers provides a simple   @Audited   annotation, you can place it on an Entity class or property of an Entity. @Audited private String description; If   @Audited   annotation is placed on a property, this property can be tracked. @Entity @Audited public class Signup implements Serializa