Saturday, September 18, 2010

Simple Session Bean - EJB 2.0

Moving Forward







In this blog, We will learn how to create a simple "Hello World" Stateless Session Bean.


A Brief Idea







A Session Bean is composed of the following parts:
  1. Home Interface : Clients use the home interface to create, remove, and find Enterprise JavaBeans instances.
  2. Component Interface : The component interface exposes an Enterprise Java Bean’s business methods to a client. The client calls the methods defined in the component interface to invoke the business logic implemented by session bean.
  3. Session Bean : The Session bean class is where you implement the business logic defined in the component interface. Session beans implement the javax.ejb.SessionBean interface.
  4. Deployment Descriptor : A deployment descriptor is an XML-based text file whose elements describe how to assemble and deploy the unit into a specific environment.
According to the EJB 2.0 specification, Component Interface and Home Interface may be either local or remote. Local Interfaces (Home and Component) are to be used by a client running in the same JVM as the EJB component.
We will discuss the ‘remote’ concept later. This is not in the scope of this blog.



Here We Go







 Home Interface : The client uses the Home to obtain instances of the bean. It extends javax.ejb.EJBLocalHome interface and declare create() method.

package example; 
import javax.ejb.CreateException;
import javax.ejb.EJBLocalHome;

public interface HelloWorldHome extends EJBLocalHome
{
            public HelloWorldLocal create() throws CreateException;
}
The return type of a create method must be the enterprise Bean's local interface type. All the exceptions defined in the throws clause of an ejbCreate method must be defined in the throws clause of the matching create method of the home interface.





Component Interface : The Component Interface is the client's view of an instance of the session bean. This interface contains the business methods declaration of the enterprise bean. It must extends javax.ejb.EJBLocalObject interface. 


package example;
import javax.ejb.CreateException;
import javax.ejb.EJBLocalObject;

public interface HelloWorldLocal extends EJBLocalObject
{
            public String sayHello() throws CreateException;
}
    

Here we have declared a method namely sayHello() which will be  implemented by our session bean.





Session Bean : The third class for EJB's is the bean implementation class. It implements the functionality provided by the component interface.


package example;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;

public class HelloWorldSessionBean implements SessionBean
{
           private static final long serialVersionUID = 1L;
           // Here is our business logic
           public String sayHello()
          {
              return "EJB Hello, world !";
           }

          // Methods of Home interface
           public void ejbCreate() {} 
          // Methods of SessionBean interface
           protected SessionContext ctx;
           public void setSessionContext(SessionContext ctx)
           {
              this.ctx = ctx;
            }
           public void ejbRemove() {}
           public void ejbActivate() {}
           public void ejbPassivate() {}
       }

 

A stateless session bean needs to have exactly one ejbCreate method with no arguments. It must also define the business methods declared in component interface [sayHello()]




Deployment Descriptor :  A deployment descriptor is used to describe and define the EJB bean.
Generally, configuration of EJB's is defined in a file namely ejb-jar.xml and placed within jar under META-INF/ejb-jar.xml.



For our example, this will be the content of ejb-jar.xml file.


<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar id="ejb-jar_ID" version="2.1" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd">
<display-name>EJB Demo</display-name>
<enterprise-beans>
<session>
      <ejb-name>HelloWorldSessionBean</ejb-name>
      <local-home>example.HelloWorldHome</local-home>
      <local>example.HelloWorldLocal</local>
      <ejb-class>example.HelloWorldSessionBean</ejb-class>
      <session-type>Stateless</session-type>
      <transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
   <method>
      <ejb-name>HelloWorldSessionBean</ejb-name>
      <method-name>*</method-name>
   </method>
   <trans-attribute>Required</trans-attribute>
 </container-transaction>
</assembly-descriptor>
</ejb-jar>

There will be one more configuration file for JNDI configuration. In case of Jboss, we use jboss.xml for JNDI configuration. This file should be placed within jar under META-INF/jboss.xml.

Now we will configure JNDI for our sample application in jboss.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 4.0//EN" "http://www.jboss.org/j2ee/dtd/jboss_4_0.dtd">
<jboss>
<enterprise-beans>
   <session>
     <ejb-name>HelloWorldSessionBean</ejb-name>
     <local-jndi-name>example.HelloWorldSession</local-jndi-name>
   </session>
</enterprise-beans>
</jboss>



Here we have one configuration file application.xml .

<application xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd"  version="5">
    <description>EJB Example</description>
    <display-name>EJB Example</display-name>
    <module>
        <ejb>EJBexample.jar</ejb>
    </module>
    <module>    
        <web>
            <web-uri>EJBexample.war</web-uri>
            <context-root>/EJBexample</context-root>
        </web>
    </module>      
</application>



Client Code
  







Here we will write client code in JSP.
I have written client.jsp for invoking EJB session bean method.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ page import="example.*, javax.naming.*, javax.rmi.PortableRemoteObject, java.util.*"%>
<%@page import="javax.ejb.CreateException"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Demo EJB</title>
</head>
<body>

<%
   String message = null;
   try
    {
 Context initialContext = new InitialContext();
HelloWorldHome home = (HelloWorldHome) initialContext.lookup("example.HelloWorldSession");
                        HelloWorldLocal myHelloWorld = home.create();
                        message = myHelloWorld.sayHello();
                        System.out.println(message);
     } catch (CreateException ce)
      {
            ce.printStackTrace();
       }
%>
<%=message %>
</body>
</html>

There is one more jsp page called index.jsp which is used as starting point of our sample application.



<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>EJB Example</title>
</head>
<body>
<a href="./jsp/client.jsp" > Click to invoke EJB </a>
</body>
</html>



Build & deploy

  




Here is the eclipse project for our sample application.

























Build :
I have used ANT to build and deploy the application into Jboss application Server.


After creating the ear file, the ear file will look like this:





















Application Server : You must install Jboss Application server in your local machine.
Link : http://www.jboss.org/jbossas/downloads/

Ant Configuration : To build and deploy the application using ANT, you have to setup ANT in your machine.
Link : http://ant.apache.org/

How to run JBoss : 

To run the application,
1. Open command prompt.
2. Go to jboss \bin folder using cd command [ F:\jboss-5.1.0.GA\bin>]
3. Type run command <Enter> [ F:\jboss-5.1.0.GA\bin>run ]
Test Application
Open a browser
Type the following URL in browser's address bar
http://localhost:8080/EJBexample/index.jsp