Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML
 
 
Search All Tutorials

 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 
Jboss
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

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 

                         

Facing Programming Problem?
Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

24 comments so far (post your own) View All Comments Latest 10 Comments:

Hi, my name is Adhie, I have the same problems with "dk" that listed below:

[LogInterceptor] EJBException in method: public abstract test.session.MyTestSession test.session.MyTestSessionHome.create() throws javax.ejb.CreateException,java.rmi.RemoteException:
javax.ejb.EJBException: Invalid invocation, check your deployment packaging, method=public abstract test.session.MyTestSession test.session.MyTestSessionHome.create() throws javax.ejb.CreateException,java.rmi.RemoteException

can you help me with this? I really need the guide for my graduated, thank you before.

Best regards,


Adhie

Posted by Adhie on Sunday, 04.27.08 @ 14:37pm | #57986

[LogInterceptor] EJBException in method: public abstract test.session.MyTestSession test.session.MyTestSessionHome.create() throws javax.ejb.CreateException,java.rmi.RemoteException:
javax.ejb.EJBException: Invalid invocation, check your deployment packaging, method=public abstract test.session.MyTestSession test.session.MyTestSessionHome.create() throws javax.ejb.CreateException,java.rmi.RemoteException

Posted by adri on Sunday, 04.27.08 @ 12:50pm | #57983

The tutorial is good indeed but I receive a class cast exception error while running JBoss. This happens in the init method of the SessionTestServlet
class while obtaining for a home reference. Please help to get around this problem.

Posted by Kaushik on Thursday, 02.21.08 @ 17:37pm | #49317


First i amtelling thanks to you.

But one error is there but i am not able to rectify it.

The error is class cast exception is occur when I create Home object in client.

please tell one solution to me.

once again Thanks for your nice effort.

regards
Sree Visveswaran
Banglore

Posted by visu on Friday, 12.7.07 @ 18:15pm | #41551

had to follow the steps mentioned in the comments though of manually deleting the files from the war folder and then running ant again to regenerate ear file. and for some reason the method name is starting with a capital letter..

Posted by vipin on Tuesday, 09.4.07 @ 10:11am | #24961

Thanks for the info Anthony (Posted by Anthony James on Tuesday, 03.27.07 @ 01:46am | #12754)

I followed your comments and it resolved my problem. I also had to manually delete the class files from the war directory.

Posted by Daz on Monday, 08.20.07 @ 12:30pm | #23763

example is very good but here u should mention the directory structure for this example otherwise its very difficult for newcomer to understand n deploy it.kindly reply me n tell me the directory structure.
thanks

Posted by Pinky on Wednesday, 07.18.07 @ 14:57pm | #21496

Hi Dear,
Very -very fantastic material which help the guys.

Posted by deepti on Thursday, 05.31.07 @ 19:07pm | #17867

21:38:18,989 INFO [EARDeployer] Started J2EE application: file:/misc/lantana3/prjstaff/deepti/JBOSS_HOME/jboss-4.0.5.GA/server/default/deploy/example3.ear
21:43:48,828 ERROR [LogInterceptor] EJBException in method: public abstract test.session.MyTestSession test.session.MyTestSessionHome.create() throws javax.ejb.CreateException,java.rmi.RemoteException:
javax.ejb.EJBException: Invalid invocation, check your deployment packaging, method=public abstract test.session.MyTestSession test.session.MyTestSessionHome.create() throws javax.ejb.CreateException,java.rmi.RemoteException
at org.jboss.ejb.StatelessSessionContainer$ContainerInterceptor.invokeHome(StatelessSessionContainer.java:175)
at org.jboss.resource.connectionmanager.CachedConnectionInterceptor.invokeHome(CachedConnectionInterceptor.java:189)
at org.jboss.ejb.plugins.StatelessSessionInstanceInterceptor.invokeHome(StatelessSessionInstanceInterceptor.java:98)
at org.jboss.ejb.plugins.CallValidationInterceptor.invokeHome(CallValidationInterceptor.java:56)
at org.jboss.ejb.plugins.AbstractTxInterceptor.invokeNext(AbstractTxInterceptor.java:125)
at org.jboss.ejb.plugins.TxInterceptorCMT.runWithTransactions(TxInterceptorCMT.java:350)
at org.jboss.ejb.plugins.TxInterceptorCMT.invokeHome(TxInterceptorCMT.java:161)
at org.jboss.ejb.plugins.SecurityInterceptor.invokeHome(SecurityInterceptor.java:145)
at org.jboss.ejb.plugins.LogInterceptor.invokeHome(LogInterceptor.java:132)
at org.jboss.ejb.plugins.ProxyFactoryFinderInterceptor.invokeHome(ProxyFactoryFinderInterceptor.java:107)
at org.jboss.ejb.SessionContainer.internalInvokeHome(SessionContainer.java:637)
at org.jboss.ejb.Container.invoke(Container.java:975)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:324)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.invocation.local.LocalInvoker$MBeanServerAction.invoke(LocalInvoker.java:169)
at org.jboss.invocation.local.LocalInvoker.invoke(LocalInvoker.java:118)
at org.jboss.invocation.InvokerInterceptor.invokeLocal(InvokerInterceptor.java:209)
at org.jboss.invocation.InvokerInterceptor.invoke(InvokerInterceptor.java:195)
at org.jboss.proxy.TransactionInterceptor.invoke(TransactionInterceptor.java:61)
at org.jboss.proxy.SecurityInterceptor.invoke(SecurityInterceptor.java:70)
at org.jboss.proxy.ejb.HomeInterceptor.invoke(HomeInterceptor.java:184)
at org.jboss.proxy.ClientContainer.invoke(ClientContainer.java:100)
at $Proxy67.create(Unknown Source)
at test.session.SessionTestServlet.doGet(SessionTestServlet.java:47)
...
...
...
The http://localhost:8080/example3/servlet/test does not give the text "Hello I am session Bean"
Can you please help me with the error. I cant understand whats gone wrong.

Posted by dk on Wednesday, 05.23.07 @ 22:24pm | #17110

hi frnd
i try to do a simple session bean to add two numbers...my client pgm is a simple java pgm...jboss 3.2.6......i got a exception ......
plse give a solution.......
This is my Exception....
-------------------------------------------------
Exception in getting home interfacejavax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial

at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.lookup(Unknown Source)
at myClient.main(myClient.java:17)
-------------------------------------------------
This is my client pgm....
-------------------------------------------------
import java.util.*;
import javax.rmi.*;
import javax.naming.*;



public class AddClient
{
public static void main(String arg[])
{
try
{


Context ctx=new InitialContext();
Object ref=ctx.lookup("Add");
AddHome home=(AddHome)PortableRemoteObject.narrow(ref,AddHome.class);
Add ejb=home.create(10,20);
int result=ejb.add();
System.out.println("Result is:"+result);
ejb.setNumber1(10);
ejb.setNumber2(12);
System.out.println("Result is:"+ejb.add());
} catch(javax.naming.NamingException ne)

{
System.out.println("Exception in getting home interface");
ne.printStackTrace();
}

catch(java.rmi.RemoteException re)
{
System.out.println("Remote Exception");
re.printStackTrace();
}
catch(javax.ejb.CreateException ce)
{
System.out.println("Exception while creating the bean instance");
ce.printStackTrace();
} catch(Exception e)
{
System.out.println("Other Exceptions");
e.printStackTrace();
}
}
}

Posted by Renjith.v.r on Wednesday, 04.18.07 @ 14:19pm | #14492

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Hot Web Programming Job

Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2007. All rights reserved.