June 18, 2011

EJB3 Stateless Session Bean with Remote access - Hello World Example

0) Refer to the EJB3 Stateless Session Bean with Local access at this link

1) In the HelloUser.java interface of the above example, replace the @Local annotation with the @Remote annotation


package info.icontraining.session;


import javax.ejb.Remote;
@Remote
public interface HelloUser {
   public String sayHello(String name);
}


2) The client in this case will not a Servlet (since the servlet object in the above example, exists in the same JVM heap as the EJB3 Session bean object, so it is not a remote object). We shall instead create a standalone Java application that executes outside the Application Server in a differente JVM Heap, effectively making the EJB Client a remote client.

Also, ensure that the EJB Project is present in the Build Path of the HelloClient Java Project. Right-click on the HelloClient Java project and select the "Java Build Path" option. Select the "Projects" tab and select add the EJB Project by clicking on the "Add..." button.

HelloClient.java


package com.yesm.client;



import java.util.Hashtable;
import javax.naming.*;
import info.icontraining.session.*;



public class HelloClient {
   public static void main(String[] args) {

      Hashtable env = new Hashtable();
      env.put("java.naming.factory.initial",
              "org.jnp.interfaces.NamingContextFactory");
      env.put("java.naming.factory.url.pkgs",
              "org.jboss.naming:org.jnp.interfaces");
      env.put("java.naming.provider.url","localhost:1099");

      Context context = null;

      try {
         context = new InitialContext(env);

         HelloUser helloUser = (HelloUser) context.lookup("MyEarApp/" +
                        HelloUserBean.class.getSimpleName() + "/remote");
         System.out.println(helloUser.sayHello("Dinesh"));
      } catch (NamingException e) {
         e.printStackTrace();
      }
   }
}


3) Deploy the EAR (Enterprise Application) according to instructions specified in the above example. Once the EAR is deployed, execute the EJB Client code to test remote accessibility of the EJB3 Stateless Session Bean.

No comments:

Post a Comment