Saturday, July 31, 2010

EJB 3 - Tutorial

Enterprise Java bean is a server-side component that encapsulates the business logic of an application. EJB can be be used when you need a scalability, data/transaction integrity and if you need to add thin clients for your application.
EJB container provides system-level services to enterprise beans, the bean developer can concentrate on solving business problems. The EJB container, rather than the bean developer, is responsible for system-level services such as transaction management and security authorization.

There are two types of EJBs in EJB3
  • Session Bean : Performs a task for a client; optionally may implement a web service
  • Message-Driven Bean : Acts as a listener for a particular messaging type, such as the Java Message Service API
There three types of Session beans as well,


  • Stateful Session Beans : The instance variables of this kind of bean represent the state of a unique client-bean session. A session bean is not shared; it can have only one client,

  • Stateless Session Beans : When a client invokes the methods of a stateless bean, the bean’s instance variables may contain a state specific to that client, but only for the duration of the invocation. Can be shared across multiple clients.

  • Singleton Session Beans : A singleton session bean is instantiated once per application, and exists for the life cycle of the application
A message-driven bean is an enterprise bean that allows Java EE applications to process messages asynchronously. It normally acts as a JMS message listener. Messages can be sent by any Java EE component or by a JMS application or system that does not use Java EE technology. Message-driven beans can process JMS messages or other kinds of messages. The most visible difference between message-driven beans and session beans is that clients do not access message-driven beans through interfaces.

Creating a stateless Enterprise Bean with NetBeans

We can create and deploy simple EJB with NetBeans and deploy it on glassfish server.


  • First create web application with NetBeans (File --> New Project --> Java Web --> Web Application).

  • Right click the project and add a Session Bean to it (New --> Session bean). This is a slateless session bean and you can add following code into it.
    package com.sun.tutorial.javaee.ejb;
    
    import java.math.BigDecimal;
    import javax.ejb.Stateless;
    
    @Stateless
    public class ConverterBean {
    
    private BigDecimal yenRate = new BigDecimal("115.3100");
    private BigDecimal euroRate = new BigDecimal("0.0071");
    
    public BigDecimal dollarToYen(BigDecimal dollars) {
      BigDecimal result = dollars.multiply(yenRate);
      return result.setScale(2, BigDecimal.ROUND_UP);
    }
    
    public BigDecimal yenToEuro(BigDecimal yen) {
      BigDecimal result = yen.multiply(euroRate);
      return result.setScale(2, BigDecimal.ROUND_UP);
    }
    
    }

  • Add a Servelt to the project (New --> Servlet).We use this servlet to call our EJB and to display result in the web browser. Add following code into the servlet.
    package converter.web;
    
    import com.sun.tutorial.javaee.ejb.ConverterBean;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.math.BigDecimal;
    import javax.ejb.EJB;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class ConverterServlet extends HttpServlet {
    
     @EJB
     ConverterBean converterBean ;
    
     public void doGet(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
    
         BigDecimal euroAmount = performOperation(request);
    
         response.setContentType("text/html");
         PrintWriter pw = response.getWriter();
         pw.println(euroAmount);
     }
    
     public BigDecimal performOperation(HttpServletRequest request) {
         try {
             String amount = request.getParameter("amount");
             if (amount != null && amount.length() > 0) {
                 BigDecimal d = new BigDecimal(amount);
                 BigDecimal yenAmount = converterBean.dollarToYen(d);
    
                 // call the ConverterBean.yenToEuro() method to get the amount in Euros
                 BigDecimal euroAmount = converterBean.yenToEuro(yenAmount);
                 return euroAmount;
             }
         } catch (Exception e){
             System.out.println(e.getMessage());
         }
         return new BigDecimal(0);
     }
    }
    
    Here we are referring ConverterBean with @EJB annotation and it uses dependency injection to obtain a reference to ConverterBean .

  • Change the index.jsp to add text box and set form action to the Servlet. Modify Index.jsp as follows.
      <body>
          <form id="form1" action="ConverterServlet">
              < div >
                  <input id="amount" name="amount" type="text" />
                  <input id="Submit1" type="submit" value="submit"/>
              </div>
          </form>
      </body>
  • Changing the web.xml to route appropriate request to servlet. Add following content to web.xml inside web-app tag.

  <servlet>
 <servlet-name>ConverterServlet</servlet-name>
 <servlet-class>
 SimpleServlet
 </servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>ConverterServlet</servlet-name>
 <url-pattern>/converterServlet</url-pattern>
 </servlet-mapping>

  • Running the application: Run the application and go to the url 
http://localhost:8080/<proj_name>/converterServlet

References:

No comments: