Monday, December 6, 2010

Writing a sample EJB Client Program using EJB 3.0

This post describes of creating a sample EJB Stateless bean and testing it in the JEE Server and it is based on EJB 3.0. Hope it will be useful..


DepartmentPersonIntf.java

package samplestateless;
public interface DepartmentPersonIntf{ //public void addNewDepartments(String name,String location); //public void addPersonInDept(String name); //public List getPersonInDept(String name);
public String getMessage(String name);
}


SampleStatelessbean.java

package samplestateless;
import javax.ejb.Stateless;import javax.ejb.Remote;import samplestateless.DepartmentPersonIntf;
@Stateless(name="SampleStatelessbean")@Remote(samplestateless.DepartmentPersonIntf.class)
public class SampleStatelessbean implements samplestateless.DepartmentPersonIntf{ public String getMessage(String name){ return "Message from Server :" +name; } public static void main(String[] args) { System.out.println("Hello World!"); }}

in META-INF create an xml sun-ejb-jar.xml with the below text.

<span><sun-ejb-jar>
<enterprise-beans>
<ejb>
<ejb-name>SampleStatelessbean</ejb-name>
<jndi-name>SampleStatelessbean</jndi-name>
</ejb>
</enterprise-beans>
</sun-ejb-jar></span>


Use the below command for creating a jar.
jar -cvf ejbtest.jar samplestateless META-INF

SampleEJBTest.java

package samplestateless;
import javax.naming.Context;import javax.naming.InitialContext;import samplestateless.DepartmentPersonIntf;import java.util.Properties;
public class SampleEJBTest{ public static void main(String[] args) throws Exception { DepartmentPersonIntf departmentPersonIntf; Properties prop = new Properties(); prop.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory"); prop.put(Context.URL_PKG_PREFIXES, "com.sun.enterprise.naming"); prop.put(Context.PROVIDER_URL, "localhost:4848"); InitialContext initialContext = new javax.naming.InitialContext(prop); departmentPersonIntf = (DepartmentPersonIntf)initialContext.lookup("SampleStatelessbean"); String message = departmentPersonIntf.getMessage("Unit Testing"); System.out.println("Hello World!"+message); }}

Create an EJBTest.jar file and deploy it in the server to test the above program.

No comments:

Post a Comment