Showing posts with label Session Beans. Show all posts
Showing posts with label Session Beans. Show all posts

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.

May 31, 2011

EJB3 Stateful Session Bean - Hello World Example

0) To setup an EJB3 project within an Enterprise Application (EAR) and deploy it to the JBoss Application Server, visit this link

1) In the MyEJBProject, create two classes - Account.java and AccountBean.java - within the ejbModule folder

Account.java


package info.icontraining.session;


import javax.ejb.*;


@Remote
public interface Account {


  public float deposit(float amount);
  public float withdraw(float amount);
  
  @Remove 
  public void remove();


}


AccountBean.java


package info.icontraining.session;


import javax.ejb.*;


@Stateful(name="AccountBean")
@Remote(Account.class)  
public class AccountBean implements Account {
   
    float balance = 0;


    public float deposit(float amount){
        balance += amount;
        return balance;
    }
 
    public float withdraw(float amount){
        balance -= amount;
        return balance;
    }

    @Remove  
    public void remove() {
        balance = 0;
    }
}


2) Within the web application, create two JSPs - accountForm.jsp and accountDetails.jsp - within the WebContent folder

accountForm.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1" %>


<html>
<body>


<h1><p align="center">Bank Transaction Form</p></h1>
<hr/><br/>

<form action="accountDetails.jsp" method="post">
  <table align="center"> 
   <tr><td>Enter the amount: <input type="text" name="amt" size="10"></td></tr>
   <tr><td><b>Select your choice:</b></td></tr>
   <tr><td><input type="radio" name="operation" value ="dep">Deposit</td></tr>
   <tr><td><input type="radio" name="operation" value ="with">Withdraw<br/></td></tr>
   <tr><td><input type="radio" name="operation" value ="balance">Check Balance<br/></td></tr>
   <tr><td><input type="submit" value="Submit"><input type="reset" value="Reset"></td></tr>
  </table>
</form>


</body>
</html>



accountDetails.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1" %>
<%@ page import="info.icontraining.session.*, javax.naming.*"%>


 <%!
     public Account account = null;
     float bal=0;


     public void jspInit() {
         try {
            InitialContext ic = new InitialContext();
            account = (Account) ic.lookup("MyEarApp/AccountBean/remote");
            System.out.println("Loaded Account Bean");
         } catch (Exception ex) {
            System.out.println("Error: "+ ex.getMessage());
         }
     }
    
     public void jspDestroy() {
        account = null;
     }
%>


   <%
    try {
       String s1 = request.getParameter("amt");
       String s2 = request.getParameter("operation");


       if (s1.equals("")) s1=null;
       
       if ( s1 != null) {
           Float amt  = new Float(s1);
                
           if(s2.equals("dep")) {
               bal=account.deposit(amt.floatValue());
               out.println("Balance is: " + bal);
               out.println("<br/><a href=accountForm.jsp>Go back</a>");


           } else if(s2.equals("with")) {
               bal=account.withdraw(amt.floatValue());
               out.println("Balance is: " + bal);
               out.println("<br/><a href=accountForm.jsp>Go back</a>");
           
           } else {        
   %>
             <p>Please select your choice</p>
                
   <%
           }
    } else {
   
           if (account != null) {  
   %>
           <p><b>Your Current Balance is:</b> <%= bal%><br/>
           <% out.println("<br/><a href=accountForm.jsp>Go back</a>"); %>
           <p>
   <%     
           }
     }
  } catch (Exception e) {
       e.printStackTrace();
  }
%>


3) Deploy the Enterprise Application comprising of the EJB Project and the Web Application.
Type the following URL in the browser and test the stateful session bean:

http://localhost:8080/MyEarApp/accountForm.jsp

EJB3 Stateless Session Bean - Hello World Example

1) Open Eclipse. Go to File > New > Project ...
Select EJB > EJB Project
Name the Project as MyEJBProject. Click Next.
Ensure that "EJB Module" with "3.0" as the version & "Java" with "5.0" as the version, checkboxes are ticked. Click Next. Click Finish.

2) In the MyEJBProject, create the following pieces of code within the ejbModule folder

HelloUser.java interface


package info.icontraining.session;


import javax.ejb.Local;


@Local  
public interface HelloUser {
      public String sayHello(String name);
}


HelloUserBean.java class



package info.icontraining.session;


import javax.ejb.Stateless;


@Stateless
public class HelloUserBean implements HelloUser {

      public String sayHello(String name) {
           return "Hello " + name + "! Welcome to EJB 3!";
      }
}


3) In your web application project (this is a different project compared to the EJB project just created above), add the following servlet code and configure it in the web.xml file

HelloUserClient.java servlet class


package info.icontraining.ejb.client;


import javax.naming.*;
import info.icontraining.session.*;
import java.io.*;
import java.util.Hashtable;
import javax.servlet.ServletException;
import javax.servlet.http.*;


public class HelloUserClient extends HttpServlet {


   public void doGet(HttpServletRequest req, HttpServletResponse res) 
                   throws ServletException, IOException {

       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"); 


       PrintWriter out = res.getWriter();

       Context context;
       try {
           context = new InitialContext(env);

           HelloUser helloUser = (HelloUser) context.lookup("MyEarApp/" 
+ HelloUserBean.class.getSimpleName() + "/local");

           out.println(helloUser.sayHello("Dinesh"));

       } catch (NamingException e) {
           e.printStackTrace();
       }
   }      
}


web.xml configuration


<servlet>
    <servlet-name>HelloUserClient</servlet-name>
    <servlet-class>info.icontraining.ejb.client.HelloUserClient</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>HelloUserClient</servlet-name>
    <url-pattern>/helloUserClient</url-pattern>
</servlet-mapping>


4) Right-click on the Web Application Project and select the "Properties" menu item.
Select "Java Build Path" from the options on the left.
Click on the "Projects" Tab.
Click the "Add..." button; Tick the "MyEJBProject" checkbox. Click OK. Again, click OK.
Any build errors in the Web Application project / servlet class will get removed.

5) Click on the "File" menu item at the top.
Select New > Project ...
Choose "J2EE" and then "Enterprise Application Project". Click Next.
Name the project as "MyEarApp". Click Next.
Check the "MyEJBProject" and the Web Application Project as the 2 modules to be added within the Enterprise Application Project. Also, check the "Generate Deployment Descriptor" option.
Click Finish.

Note: In Eclipse Helios, after creating the Enterprise Application Project, right click on the project, select Properties. In the pop-up window, select "Deployment Assembly" on the left. Then click on the "Add..." button and select choose Project and click Next. Select the 2 projects - the EJB Project (MyEJBProject) and the web application project together (by pressing down the CTRL key). Click Finish.

6) Open the application.xml file within the new created EAR project - MyEarApp - within the EarContent/META-INF folder.
Modify the <context-root> element of the web application to /MyEarApp

7) Deploy the MyEarApp project to the JBoss Application Server and test the EJB by typing the following URL in the browser:

http://localhost:8080/MyEarApp/helloUserClient