Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Jboss developing a Session Bean and a Servlet and deploy the web application on JBoss 3.0

Related Tutorials


 
 

Share on Google+Share on Google+

developing a Session Bean and a Servlet and deploy the web application on JBoss 3.0

Advertisement
developing a Session Bean and a Servlet and deploy the web application on JBoss 3.0 Writing Stateless Session Bean and Calling through Servlet Previous Tutorial Index Next In this lesson I will show you how to develop a Stateless Session Bean and

Writing Stateless Session Bean and Calling through Servlet

     

In this lesson I will show you how to develop a Stateless Session Bean and a Servlet and deploy the web application on JBoss 3.0 Server. 

Our application is thin-client multitiered consisting of jsp, servlet and session bean. 

In the next lesson we will create Entity bean. So first of all I will explain how to create Session bean and write the deployment descriptor.

Writing Session Bean

Session Bean interacts with the client and is non persistent in nature. If server crashes all the data stored in Session Bean are lost. But Entity Beans are persistent in nature and in case sever crashes Entity Bean reconstruct its data from the underlying database. Session Beans are used to handle the client request and manage the session and Entity Beans are used to do database processing.

Session beans are of two types "Stateful" and "Stateless". A Stateful session bean preserve the information about its content and values between clients calls. Example of Stateful session bean may be Shopping Cart Session bean. Stateless session bean do not preserve the information between the client calls.

Session Bean is consists of following components:

  1. Enterprise Bean remote interface
     

  2. Enterprise Bean Home interface
     

  3. Enterprise bean class definition
      

  4. Deployment descriptors

Enterprise Bean remote interface

All remote interfaces must extend javax.ejb.EJBObject. Remote interface is the client view of session bean. Methods defined in the remote interface are accessible to the client. In our example we have defined the  SayHello() method for calling from servlet. SayHello method is implemented in bean class.

/*
* MyTestSession.java
*
*/
package test.session;
import java.lang.*;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext; 
/**
* @author Deepak Kumar
* @Web http://www.roseindia.net
* @Email deepak@roseindia.net
*/
public interface MyTestSession extends javax.ejb.EJBObject{
public java.lang.String SayHello() throws java.rmi.RemoteException;
}

Enterprise Bean Home interface

All home interfaces must extend javax.ejb.EJBHome. 'create()' method of home interface of the application enables the client to create and remove the session object. 

/*
* MyTestSessionHome.java
*
*/
package test.session;
import java.lang.*;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;

/**
* @author Deepak Kumar
* @Web http://www.roseindia.net
* @Email deepak@roseindia.net
*/
public interface MyTestSessionHome extends javax.ejb.EJBHome{
public static final String COMP_NAME="java:comp/env/ejb/test/MyTestSession";
public static final String JNDI_NAME="ejb/test/MyTestSessionBean";
public test.session.MyTestSession create() throws javax.ejb.
CreateException, java.rmi.RemoteException;
} 

Enterprise Bean class

All Bean class are defined as public and implements the javax.ejb.SessionBean. In the bean class we have defined SayHello() method, this method is called from our servlet. Besides this method other required methods which is to be implemented are:

  1. ejbCreate()

  2. ejbRemove()

  3. ejbActivate()

  4. ejbPassivate()

  5. setSessionContext(SessionContext aContext)

For the time being these methods are left blank but for advance programming these are used.

/*
* SessionBean.java
*
*/
package test.session;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
/**
* @author Deepak Kumar
* @Web http://www.roseindia.net
* @Email deepak@roseindia.net
*/
public class MyTestSessionBean implements SessionBean{
public void ejbCreate() throws CreateException {
}
public String SayHello(){
String msg="Hello! I am Session Bean";
System.out.println(msg);
return msg;
}
 public void setSessionContext( SessionContext aContext ) throws EJBException {
}
 public void ejbActivate() throws EJBException {
}
public void ejbPassivate() throws EJBException {
}
public void ejbRemove() throws EJBException {
}
}

Jar Descriptor File

For creating example3.jar ejb-jar.xml and jboss.xml files are required which explains the content of jar file.

ejb-jar.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE 
ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" 
"http://java.sun.com/dtd/ejb-jar_2_0.dtd">

<ejb-jar>

 <description>Example 3</description>
 <display-name>Example 3</display-name>

<enterprise-beans>

<!-- Session Beans -->
<session id="test_MyTestSession">
<display-name>My Test Session Bean</display-name>
<ejb-name>test/MyTestSession</ejb-name>
<home>test.session.MyTestSessionHome</home>
<remote>test.session.MyTestSession</remote>
<ejb-class>test.session.MyTestSessionBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>

</enterprise-beans>

<assembly-descriptor>

</assembly-descriptor>

</ejb-jar>

Above deployment descriptor defines remote, home and bean class for the bean and assigns a name 'test/MyTestSession' to the session bean. Please note that bean of Stateless type and is defined by:
<session-type>Stateless</session-type>

jboss.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS//EN" 
 "http://www.jboss.org/j2ee/dtd/jboss.dtd">

<jboss>

<enterprise-beans>

<session>
<ejb-name>test/MyTestSession</ejb-name>
<jndi-name>ejb/test/MyTestSessionBean</jndi-name>
</session>

</enterprise-beans>

<resource-managers>
</resource-managers>

</jboss>

The jboss deployment descriptor assigns jndi name ' ejb/test/MyTestSessionBean' to the 'test/MyTestSession' bean.

Writing Servlet class and Web/Ear component

Our servlet access the session bean and calls SayHello() method of the session bean and prints the return string on the browser. 

Here is the code of our servlet.

/*
* SessionTestServlet.java
*
*/
package test.session;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import javax.naming.*;
import javax.rmi.PortableRemoteObject;

/**
* @author Deepak Kumar
* @Web http://www.roseindia.net
* @Email deepak@roseindia.net
*/

public class SessionTestServlet extends HttpServlet {
			MyTestSessionHome testSessionBean;

	public void init(ServletConfig config) throws ServletException{
		//Look up home interface
		try {
			InitialContext ctx = new InitialContext();
			Object objref = ctx.lookup("ejb/test/MyTestSessionBean");
			testSessionBean = (MyTestSessionHome)PortableRemoteObject.narrow(objref, 
			MyTestSessionHome.class);
		} catch (Exception NamingException) {
		NamingException.printStackTrace();
	}
}
	public void doGet (HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException
		{
		PrintWriter out;
		response.setContentType("text/html");
		String title = "EJB Example";
		out = response.getWriter();

		out.println("<html>");
		out.println("<head>");
		out.println("<title>Hello World Servlet!</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<p align=\"center\"><font size=\"4\" color=\"#000080\">"+"
					Servlet Calling Session Bean</font></p>");

	try{	
		MyTestSession beanRemote;
		beanRemote = testSessionBean.create();
		out.println("<p align=\"center\"> Message from Session Bean is: <b>"
						 + beanRemote.SayHello() + "</b></p>"); 
		beanRemote.remove();
		}catch(Exception CreateException){
		CreateException.printStackTrace();
		}
		out.println("<p align=\"center\">"+
			"<a href=\"javascript:history.back()\">Go to Home</a></p>");
		out.println("</body>");
		out.println("</html>");
		out.close();
	}
	public void destroy() {
		System.out.println("Destroy");
	}
}

Web-Component Descriptor File

For creating example3.war web.xml and jboss-web.xml files are required which explains the content of web archinve.

web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE 
   web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
   "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>SessionServlet</servlet-name>
<display-name>Simple Session Servlet</display-name>
<servlet-class>test.session.SessionTestServlet</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>
<servlet-name>SessionServlet</servlet-name>
<url-pattern>/servlet/test</url-pattern>
</servlet-mapping>

<session-config>
<session-timeout>0</session-timeout>
</session-config>

</web-app>

Above deployment descriptor defines servlet class for the servlet and assigns url pattern '/servlet/test' to the servlet. We call the servlet by tying <context>/servlet/test in the browser.

jboss-web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jboss-web PUBLIC "-//JBoss//DTD Web Application 2.2//EN" 
"http://www.jboss.org/j2ee/dtd/jboss-web.dtd">

<jboss-web>

</jboss-web> 

J2EE Enterprise Archive (ear) Descriptor File

For creating example3.ear application.xml, file is required which explains the content of enterprise archive.

application.xml file:

<?xml version="1.0" encoding="ISO-8859-1"?>

<application>
<display-name>Example 3 </display-name>
<module>
<web>
<web-uri>example3.war</web-uri>
<context-root>/example3</context-root>
</web>
</module>

<module>
<ejb>example3.jar</ejb>
</module>

</application>

Above deployment descriptor describes the content of example3.ear file which contains to modules one web module example3.war and one jar file example3.jar.

Writing ant build file and assembling the application into enterprise archive example3.ear

I have written ant build for compiling all source files and assembling into enterprise archive eample3.ear. Here is the code of ant build file:

build.xml file:

<?xml version="1.0"?>
<!-- ==================================================== -->
<!-- Build file for our first web application -->
<!-- build.xml, Saturday, July 20, 2002 -->
<!-- Author: Deepak Kumar -->
<!-- Email : deepak@roseindia.net -->
<!-- Url : http://www.roseindia.net -->
<!-- ==================================================== -->


<project name="Jboss 3.0 tutorial series" default="all" basedir=".">

<target name="init">
<property name="dirs.base" value="${basedir}"/>
<property name="classdir" value="${dirs.base}/build/src"/>
<property name="src" value="${dirs.base}/src"/>
<property name="web" value="${dirs.base}/web"/>
<property name="deploymentdescription" value="${dirs.base}/deploymentdescriptors"/>

<property name="warFile" value="example3.war"/>
<property name="earFile" value="example3.ear"/>
<property name="jarFile" value="example3.jar"/>


<property name="earDir" value="${dirs.base}/build/ear"/>
<property name="warDir" value="${dirs.base}/build/war"/>
<property name="jarDir" value="${dirs.base}/build/jar"/>



<!-- Create Web-inf and classes directories -->
<mkdir dir="${warDir}/WEB-INF"/>
<mkdir dir="${warDir}/WEB-INF/classes"/>

<!-- Create Meta-inf and classes directories -->
<mkdir dir="${earDir}/META-INF"/>
<mkdir dir="${jarDir}/META-INF"/>
</target>

<!-- Main target -->
<target name="all" depends="init,build,buildWar,buildJar,buildEar"/>


<!-- Compile Java Files and store in /build/src directory -->
<target name="build" >
<javac srcdir="${src}" destdir="${classdir}" debug="true" includes="**/*.java" />
</target>

<!-- Create the web archive File -->
<target name="buildWar" depends="init">
<copy todir="${warDir}/WEB-INF/classes">
<fileset dir="${classdir}" includes="**/*.class" /> 
</copy>

<copy todir="${warDir}/WEB-INF">
<fileset dir="${deploymentdescription}/web/" includes="web.xml,jboss-web.xml" /> 
</copy>

<copy todir="${warDir}">
<fileset dir="${web}" includes="**/*.*" /> 
</copy>

<!-- Create war file and place in ear directory -->
<jar jarfile="${earDir}/${warFile}" basedir="${warDir}" />


</target>


<!-- Create the jar File -->
<target name="buildJar" depends="init">
<copy todir="${jarDir}">
<fileset dir="${classdir}" includes="**/*.class" /> 
</copy>

<copy todir="${jarDir}/META-INF">
<fileset dir="${deploymentdescription}/jar/" includes="ejb-jar.xml,jboss.xml" /> 
</copy>

<!-- Create jar file and place in ear directory -->
<jar jarfile="${earDir}/${jarFile}" basedir="${jarDir}" />


</target>


<!-- Create the ear File -->
<target name="buildEar" depends="init">
<copy todir="${earDir}/META-INF">
<fileset dir="${deploymentdescription}/ear" includes="application.xml" /> 
</copy>

<!-- Create ear file and place in ear directory -->
<jar jarfile="${basedir}/${earFile}" basedir="${earDir}" />
</target>

</project>

Above file does every thing for you and creates example3.ear file in the example3 directory. To assemble the application simple run the ant build utity.

To deploy the application copy the file into the deploy (JBOSS_HOME/server/default/deploy) directory of JBoss 3.0. 

To test the application type http://localhost:8080/example3 in the browser and click on the link provided in the index.jsp. Your browser should show the following screen:

Download the code of this lesson.

After completing this lesson you are able to:

  1. Write session bean
  2. Write a servlet
  3. Call session bean from servlet
  4. Write the deployment descriptor files
  5. Write ant build file
  6. Assemble enterprise archive, deploy and test on the JBoss 3 server 
Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 30, 2005

Related Tutorials

Discuss: developing a Session Bean and a Servlet and deploy the web application on JBoss 3.0   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com