Search This Blog

Friday, September 16, 2016

Create First CDI Application

1- Create new Netbeans Project named "CDI_JavaOne16_TUT3287_Demo"

2- Edit the "Web.xml"

<servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>

and 

<welcome-file-list>
        <welcome-file>index.xhtml</welcome-file>
</welcome-file-list>


3- Run the project
Is it works OK

4- Start our coding

5- create a POJO Bean named "HelloWorld"
5.1 - add method
    public String sayHello(){
        return "Hello User from CDI !";
    }


6- create Managed bean for the page named "HelloManagedBean" with request scope
import javax.enterprise.context.RequestScoped;
6.1 - Inject the bean
    @Inject
    private HelloWorld helloWorld;

6.1 - add action method
    public String sayHelloAction() {
        System.out.println("com.javaone.cdi.secOne.hello.beans.HelloManagedBean.sayHelloAction() : " + helloWorld.sayHello());
        return null;
    }


7- craete page named "HelloPage.xhtml"
7.1 - Add <h:form>
7.2 - add command button <h:commandButton value="Say Hello" action="#{helloManagedBean.sayHelloAction}"/>


8- Activate CDI by adding the beans.xml
8.1 - update the configuration to be  bean-discovery-mode to be "all"
<?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_1_1.xsd"
       bean-discovery-mode="all">
</beans>


9- Run


Post a Comment