Session EJB Example on Glassfish - No Annotations

Aim
The aim of this Java Session Bean tutorial is to create simple stateless (and stateful) Enterprise Java Beans or EJBs, deploy it to a Glassfish app server and then call it's remote interface via a java client. We will be building this bean from the ground up with an ejb-jar.xml and without the use of Annotations( @Remote etc). Once you learn the basic you can take the short-cuts. Leave any questions or problems as comments and I will endeavour to answer them. The sister tutorial for an Entity Bean can be found at CMP EJB Example.

Assumptions
This article assumes that you have Galssfish 2 installed and a domain configured. Please see Installing and Setting up Glassfish 2 for more details. For purposes of this example the glassfish domain is running on port 8082 and the project directory is EJBHelloWorld.


Versions used in this example
Sofware/ComponentImage
Windows XP SP2N/A
Glassfish 2glassfish-installer-v2.1-b60e-windows.jar
JDK 1.5.0N/A
Links to these files can be found here

Although this is a quick 'helloworld' tutorial we will not sacrifice neatness for speed - so all the source files, class files etc will be kept in separate directories and as clean as possible. You will thank me for this later.

Create this webapp directory structure in your working directory- similar to something you would get from eclipse. The structure used in this example is given below. GlassfishWSHelloworld will be referred to as your project or working directory. Create this structure.

EJBHelloWorld
_|_bean_src
_|__|_SessionBeanExample.java
_|__|_SessionBeanHomeExampleI.java
_|__|_SessionBeanExampleI.java
_|_bean_bin
_|__|_META-INF
_|__|__|_ejb-jar.xml
_|__|__|_sun-ejb-jar.xml
_|_client_src
_|__|_SessionBeanClient.java
_|_client_bin


The Glassfish app server is installed in the D:\downloads\glassfish directory for this tutorial.

Write and compile the Bean files
  1. Write the remote interface and save it under bean_src as SessionBeanExampleI.java. The 'SayHello' method will be the exposed method in this example.
     1. package ejb.sessionbeanexample;
     2. 
     3. import java.rmi.*;
     4. import javax.ejb.*;
     5. 
     6. public interface SessionBeanExampleI extends EJBObject{
     7.     public String SayHello(String s) throws RemoteException;
     8. }
    Hide line numbers
  2. `
  3. Write the home interface and save it under bean_src as SessionBeanHomeExampleI.java.
     1. package ejb.sessionbeanexample;
     2. 
     3. import java.rmi.*;
     4. import javax.ejb.*;
     5. 
     6. public interface SessionBeanHomeExampleI extends EJBHome{
     7.     public SessionBeanExampleI create() throws CreateException, RemoteException;
     8. }
    Hide line numbers
  4. `
  5. Complete the bean implementation and save it under bean_src as SessionBeanExample.java.
     1. package ejb.sessionbeanexample;
     2.   
     3. import javax.ejb.*;
     4. import java.io.Serializable;
     5. import java.util.*;
     6. import java.rmi.*;
     7.   
     8. public class SessionBeanExample implements SessionBean {
     9.   
    10.     private SessionContext context;
    11.   
    12.     public void ejbActivate() {
    13.         System.out.println("ejb - activate");
    14.     }
    15.   
    16.     public void ejbRemove() {
    17.       System.out.println("ejb - remove");
    18.     }
    19.   
    20.     public void ejbPassivate() {
    21.       System.out.println("ejb - passivate");
    22.     }
    23.   
    24.     public void setSessionContext(SessionContext context) {
    25.         System.out.println("ejb - setSessionContext");
    26.         this.context = context;
    27.     }
    28.     
    29.     public void ejbCreate () {
    30.       System.out.println("ejb - create");
    31.     }
    32. 
    33.     public String SayHello(String s)throws RemoteException{
    34.         return(s+" echo from java bean");
    35.     }
    36. }
    Hide line numbers
  6. `
  7. Compile the code and install the classes into the bean_bin using the cmd below.

    ..workspace\EJBHelloWorld\bean_src>javac -extdirs D:\downloads\glassfish\lib -d ..\bean_bin *.java
  8. `
  9. Create the deployment descriptor ejb-jar.xml. Save this under the bean_bin/META-INF directory. For a stateful bean simply change the value in the session-type tag to "Stateful" from "Stateless."
     1. <?xml version="1.0" encoding="UTF-8"?>
     2. <ejb-jar>
     3.    <display-name>Session Bean Example</display-name>
     4.    <enterprise-beans>
     5.       <session>
     6.         <description>Simple session bean example</description>
     7.         <ejb-name>SessionBeanExample</ejb-name>
     8.         <home>ejb.sessionbeanexample.SessionBeanHomeExampleI</home>
     9.         <remote>ejb.sessionbeanexample.SessionBeanExampleI</remote>
    10.         <ejb-class>ejb.sessionbeanexample.SessionBeanExample</ejb-class>
    11.         <session-type>Stateless</session-type>
    12.         <transaction-type>Bean</transaction-type>
    13.       </session>
    14.    </enterprise-beans>
    15. </ejb-jar>
    Hide line numbers
  10. `
  11. Create the sun-ejb-jar.xml file and save this under the bean_bin\WEB-INF folder too.
     1. <?xml version="1.0" encoding="UTF-8"?>
     2. <sun-ejb-jar>
     3. <enterprise-beans>
     4.     <ejb>
     5.         <ejb-name>SessionBeanExample</ejb-name>
     6.         <jndi-name>ejb/sessionbeanexample</jndi-name>
     7.     </ejb>
     8. </enterprise-beans>
     9. </sun-ejb-jar>
    Hide line numbers

Deploy the EJB in Glassfish
We are going to take a short cut and deploy the bean_bin directory instead of jar-ring it up and deploying as a .war or .jar file.
  1. Login to the Glassfish admin console. Please see Installing and Setting up Glassfish 2
  2. `
  3. Under Applications->EJB Modules select deploy. Under "Location" select "Local packaged file or directory..." and select "Browse Folders". Now navigate to your working directory (EJBHelloWorld) and select the bean_bin directory and press "Choose folder." This shold deploy the bean without any issues. If there is a problem look at the server.log in the log directory in your Glassfish domain.
  4. `
  5. To make sure go to the "bin" diretory under your glassfish installation and run asadmin with list-jndi-entries.

    D:\downloads\glassfish\bin>asadmin list-jndi-entries --context ejb

    Jndi Entries for server within ejb context:
    mgmt: com.sun.enterprise.naming.TransientContext
    sessionbeanexample: javax.naming.Reference
    Command list-jndi-entries executed successfully.

Write and compile the Client
  1. Write client and save it under the client_src direcotry as SessionBeanClient.java. I have added the remove method for completeness. This will remove a "Stateful" bean but will be ignored by a "Stateless" bean. You can check out the Glassfish logs to see this. 
     1. import java.util.*;
     2. import java.io.*;
     3. import javax.naming.*;
     4. 
     5. import ejb.sessionbeanexample.SessionBeanHomeExampleI;
     6. import ejb.sessionbeanexample.SessionBeanExampleI;
     7. 
     8. public class SessionBeanClient {
     9. 
    10.     public static void main(String[] args) throws Exception{
    11.         (new SessionBeanClient()).Go();
    12.     }
    13.     
    14.     public void Go() throws Exception {
    15.         Properties props = new Properties();
    16.         
    17.         props.put(Context.PROVIDER_URL,"iiop://127.0.0.1:3700");
    18.         props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory");
    19.         
    20.         InitialContext ctx = new InitialContext(props);
    21.         
    22.         SessionBeanHomeExampleI beanhome = (SessionBeanHomeExampleI) ctx.lookup("ejb/sessionbeanexample");
    23.         
    24.         SessionBeanExampleI bean = beanhome.create();
    25. 
    26.         System.out.println(bean.SayHello("Hi Partner"));
    27.         
    28.         bean.remove(); //For statefull
    29.       
    30.     }
    31. }
    Hide line numbers
  2. `
  3. open a promt to the "client_src" directory and Compile the code. Use the "-d" ooption to copy the class to the client_bin directory.
    ..workspace\EJBHelloWorld\client_src>javac -extdirs D:\downloads\glassfish\lib
    -d ..\client_bin -cp ..\bean_bin SessionBeanClient.java

Running the client
  1. Open a command into the client_bin directory and run the application.
    ..workspace\EJBHelloWorld\client_bin>java -Djava.ext.dirs=D:\downloads\glassfish\lib -cp ..\bean_bin;. SessionBeanClient
  2. `
  3. You should see "Hi Partner echo from java bean" in the console. Also, if you have a look at the Glassfish server.log you will be able to see what callbacks have been triggered. If you deployed the bean as a "Stateful" bean you should see "ejbRemove" getting called. If you deployed it as a "Stateless" bean then "ejbRemove" will only get called at the descretion of the container. We're now done. If you are seeing errors check the server.log.

Back to the tutorial trail | Home

5 comments:

java-ejb-servlet-jsp-example said...

I wish to link an article with complete and simple tutotial for using the main different java ee tecnologies:

http://programmaremobile.blogspot.com/2009/01/java-ee-how-to-use-ejb-and-web.html

It show how integrate EJB: entity + session bean with a web module: servlet + jsp

Anonymous said...

thanks for sharing this site. various kinds of ebooks are available here
http://feboook.blogspot.com

Johnny Goh HY said...

I've the following error at the Java Client...

org.glassfish.enterprise.iiop.impl.IIOPSSLSocketFactory
SEVERE: iiop.init_exception

sani said...

i m making a project on deadlock handling mechanisms....in which i need to handle trnsactions....plz can anyone tell me how to start .........
i m thinking of wrkng on ejb but it is not running in netbeans......wat else shall i download to mke it run.....plz cn any1 tel me.....

Naviya Nair said...

Very interesting and good Explanation
ASP NET Training
ASP NET Training
ASP NET Online Training
C-Sharp Training
Dot Net Training in Chennai
Online .Net Training


MVC Training
WCF Training
Web-API Training
LINQ Training
Entity Framework
Training

Dot Net Interview Questions