Hi,

As JBoss AS7 is very new And most powerful application server with many changes in it. JBossAS7 web profile is fully EE6 Certified however the JBoss AS7 full profile will be released soon with the full EE6 capabilities. CDI (Conextual Dependency Injection) is one of the most attractive feature of EE6. Managed beans are a key concept introduced in Java EE6. More details on CDI specification can be found in the following link: http://jcp.org/en/jsr/detail?id=299

So here we are going to see a very simple demo in which we will create our own Bean using “@javax.inject.Named” annotation and we will define it’s scope as “@javax.enterprise.context.SessionScoped”. Then we will try to inject this Plain Bean inside our HttpServlets using annotation “@javax.inject.Inject”. We will also see how we can develop, build, deploy and test this simple WAR file.

Features To Discuss.

In this example we will mainly focus on following points

Point-1). Here we are using JBoss AS7 latest build “jboss-as-7.1.0.Beta1” which can be downloaded from the following link: http://www.jboss.org/jbossas/downloads

Point-2). How to use and develop Servlets3.0 annotations without writing “web.xml” file.

Point-3). How to create our own Managed Beans using annotations @Named.

Point-4). Also we will see how to define the scope of our Beans using annotation @SessionScope.

Point-5). How to inject a Named Bean inside a Servlet using @Inject Annotation.

Point-6). For creating and using Named beans we must create at least one empty “beans.xml” file inside our applications “WEB-INF” directory, If it is a Web Application. For EJB Based application it can be placed inside the “META-INF” directory. For Plain Jar files it can be placed inside the jars present inside the “lib” directory.

Developing TestCase

Step1). Create a directory somewhere in your filesystem like “/home/userone/CDI_Demo” where we will place our application build related stuff. Then create another directory “src” inside “/home/userone/CDI_Demo” where we will be placing our source codes and JSPs.
Just place an empty “beans.properties” file inside “/home/userone/CDI_Demo/src”

Step2). Create Bean class “TestBean.java” as following inside the “/home/userone/CDI_Demo/src” directory.

package beans;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

@Named
@SessionScoped
public class TestBean implements Serializable 
   {
	private static final long serialVersionUID = 1L;
	private String beanParam="Hi MiddlewareMagic !!!";

        public TestBean()
         {
    	   System.out.println("nt TestBean which is CDI Bean instentiated.");
         }
    
	public String getBeanParam() 
         {
	    System.out.println("nt getBeanParam() called.");
	    return beanParam;
	 }

	public void setBeanParam(String beanParam) 
         {
	    System.out.println("nt setBeanParam("+beanParam+") called.");
	    this.beanParam = beanParam;
	 }	
   }

Step2-A) Make sure that at least one empty file “beans.xml” need to be placed inside the “WEB-INF” directory of your application in order to web beans work.
So create an empty file with name “beans.xml” and then place it inside “/home/userone/CDI_Demo/src” then later while Build phase of the application we will put this file inside “WEB-INF” directory of our web application.

Step3). Now we will create a Simple HttpServlet class “TestServlet.java” inside “/home/userone/CDI_Demo/src” directory as following:

package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;

import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.annotation.WebServlet;

@WebServlet(description = "TestServlet Description", urlPatterns = { "/TestServlet" })
public class TestServlet extends HttpServlet {
	
	@Inject 
	private beans.TestBean testBean;
	
	private static final long serialVersionUID = 1L;
        public TestServlet() 
        {
          super();
          System.out.println("TestServlet Initialized & Instentiated.");
        }

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
        {
          PrintWriter out=response.getWriter(); 
	  out.println("testBean.getBeanParam() = "+testBean.getBeanParam());
          testBean.setBeanParam("Hello, MiddlewareMagic");
          out.println("testBean.getBeanParam() = "+testBean.getBeanParam());
	}
}

Step4). Now we will write another simple Servlet “TestServletTwo.java” to check whether the Named Bean is present inside the SesionScope or not? Place this file as well inside the “/home/userone/CDI_Demo/src” directory as following:

package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;

import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.annotation.WebServlet;

@WebServlet(description = "TestServletTwo Description", urlPatterns = { "/TestServletTwo" })
public class TestServletTwo extends HttpServlet {
	
	@Inject 
	private beans.TestBean testBean;
	
	private static final long serialVersionUID = 1L;
        public TestServletTwo() 
        {
          super();
          System.out.println("TestServletTwo Initialized & Instentiated.");
        }

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
        {
          PrintWriter out=response.getWriter(); 
	  out.println("testBean.getBeanParam() = "+testBean.getBeanParam());
	}
}

Step5). Now we will write a simple “index.jsp” page to just provide a link to access the “TestServlet” , Place this file as well inside the “/home/userone/CDI_Demo/src” directory as following:

<html>
  <head> 
    <title>CDI Demo</title>
  </head>
  <body>
      <a href="TestServlet">Click Here !!!</a>
  </body>
</html>

Step6). Now the most important part, here we are going to develop “build.xml” ANT file, which will build, deployour webapplication on the JBoss AS7.1 Beta Server, so write the following “build.xml” file inside “/home/userone/CDI_Demo” directory.

<project name="CDI_Demo" default="deploy">
<property name="jboss.home" value="/home/userone/jboss-as-7.1.0.Beta1" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="basedir" value="." />
<property name="tmp.dir" value="tmp" />
<property name="output.dir" value="build" />
<property name="src.dir" value="src" />
<property name="war.name" value="EE6Feature_CDIDemo.war" />

   <path id="jboss.classpath">
     <fileset dir="${jboss.module.dir}">
        <include name="**/*.jar"/>
     </fileset>  
   </path>

        <target name="init">
           <delete dir="${output.dir}" />
           <mkdir dir="${output.dir}" />
           <delete dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}" />
        </target>
	 
        <target name="build" depends="init">
           <mkdir dir="${tmp.dir}/WEB-INF/classes"/>
           <javac srcdir="${src.dir}" destdir="${tmp.dir}/WEB-INF/classes"  includes="*.java" classpathref="jboss.classpath" />
           <copy file="${src.dir}/index.jsp" tofile="${tmp.dir}/index.jsp"/>
           <copy file="${src.dir}/TestServlet.java" todir="${tmp.dir}/WEB-INF/classes"/>
           <copy file="${src.dir}/TestServletTwo.java" todir="${tmp.dir}/WEB-INF/classes"/>
           <copy file="${src.dir}/TestBean.java" todir="${tmp.dir}/WEB-INF/classes"/>

           <!-- Need to place at lease one empty "beans.xml" file inside WEB-INF -->
           <copy file="${src.dir}/beans.xml" todir="${tmp.dir}/WEB-INF"/>
   
           <jar jarfile="${tmp.dir}/${war.name}" basedir="${tmp.dir}" compress="true" />
           <copy file="${tmp.dir}/${war.name}" tofile="${output.dir}/${war.name}"/>

           <delete includeEmptyDirs="true">
              <fileset dir="${tmp.dir}"/>
           </delete> 
        </target>

        <target name="deploy" depends="build">
            <echo message="*******************  Deploying the WAR file ${war.name} *********************" />  
            <echo message="********** ${output.dir}/${war.name} to ${jboss.home}/standalone/deployments **********" />  
            <copy todir="${jboss.home}/standalone/deployments/">
                <fileset dir="${output.dir}/">
                  <include name="${war.name}"/> 
                </fileset>
            </copy>
            <echo message="*******************  Deployed Successfully   *********************" />  
        </target>
</project>

NOTE: The only change in the above file you need to do is to change the “jboss.home” directory path in the second line of the above script to point to your own JBoss AS7 directory.

Step7). Now before running your ANT script to build and deploy the above webapplication you should have the ANT as well as JAVA set in the $PATH variable of the Shell / command prompt as following:

For Unix Based OS:
export PATH=/home/userone/jdk1.6.0_21/bin:/home/userone/org.apache.ant_1.6.5/bin:$PATH

For Windows Based OS:
set PATH=C:/jdk1.6.0_21/bin;C:/org.apache.ant_1.6.5/bin;%PATH%

Step8). Now once the PATH is set In the command/Shell prompt you can move inside the directory “/home/userone/CDI_Demo” and then run the ant to build the webservice. by running the command “ant build”

[userone@localhost EE6_Async_Servlet_Demo]$ ant deploy
Buildfile: /home/userone/CDI_Demo/build.xml

init:
   [delete] Deleting directory /home/userone/CDI_Demo/build
    [mkdir] Created dir: /home/userone/CDI_Demo/build
    [mkdir] Created dir: /home/userone/CDI_Demo/tmp

build:
    [mkdir] Created dir: /home/userone/CDI_Demo/tmp/WEB-INF/classes
    [javac] /home/userone/CDI_Demo/build.xml:25: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
    [javac] Compiling 3 source files to /home/userone/CDI_Demo/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/CDI_Demo/tmp
     [copy] Copying 1 file to /home/userone/CDI_Demo/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/CDI_Demo/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/CDI_Demo/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/CDI_Demo/tmp/WEB-INF
      [jar] Building jar: /home/userone/CDI_Demo/tmp/EE6Feature_CDIDemo.war
     [copy] Copying 1 file to /home/userone/CDI_Demo/build

deploy:
     [echo] *******************  Deploying the WAR file EE6Feature_CDIDemo.war *********************
     [echo] ********** build/EE6Feature_CDIDemo.war to /home/userone/jboss-as-7.1.0.Beta1/standalone/deployments **********
     [copy] Copying 1 file to /home/userone/jboss-as-7.1.0.Beta1/standalone/deployments
     [echo] *******************  Deployed Successfully   *********************

BUILD SUCCESSFUL
Total time: 2 seconds

Step9). Now you will see the following kind of output on your JBoss AS7.1 console which means the application is deployed successfully:

11:41:27,741 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-2) Starting deployment of "EE6Feature_CDIDemo.war"
11:41:27,760 INFO  [org.jboss.weld] (MSC service thread 1-5) Processing CDI deployment: EE6Feature_CDIDemo.war
11:41:27,770 INFO  [org.jboss.weld] (MSC service thread 1-3) Starting Services for CDI deployment: EE6Feature_CDIDemo.war
11:41:27,775 INFO  [org.jboss.weld] (MSC service thread 1-3) Starting weld service
11:41:27,859 INFO  [org.jboss.web] (MSC service thread 1-2) registering web context: /EE6Feature_CDIDemo
11:41:27,898 INFO  [org.jboss.as.server.controller] (DeploymentScanner-threads - 1) Replaced deployment "EE6Feature_CDIDemo.war" with deployment "EE6Feature_CDIDemo.war"

Step10). Now access the WebApplication like following :
http://localhost:8080/EE6Feature_CDIDemo/TestServlet
AND then
http://localhost:8080/EE6Feature_CDIDemo/TestServletTwo

You will notice that the TestBean is injected inside these servlets using Session Scope.

.
.
Thanks
Middleware Magic Team

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.