Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Wiki Markup
{scrollbar}

Sample of a Stateless Session Bean in EJB 3.0

This sample will demonstrate the following new features from EJB 3.0

  1. Elimination of the requirement for EJB component interfaces for session beans. The required business interface for a session bean can be a plain Java interface rather than an EJBObject, EJBLocalObject, or java.rmi.Remote interface.
  2. Elimination of the requirement for home interfaces for session beans.
  3. Encapsulation of environmental dependencies and JNDI access through the use of annotations, dependency injection mechanisms, and simple lookup mechanisms.
  4. Introduction of Java metadata annotations to be used as an alternative to deployment descriptors.

Calculator Implementation

Calculator.java: A stateless session bean that implements a simple java interface instead of an EJB component interface like EJBObject, EJBLocalObject or java.rmi.Remote. By annotating this class as a @Stateless session there is no need for a deployment descriptor to describe it separately. This class implements both a local and remote business interface, namely CalculatorLocal and CalculatorRemote.

...

Code Block
java
java
borderStylesolid
titleCalculatorServlet.java
package org.apache.geronimo.samples.calculator;

import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.geronimo.samples.slsb.calculator.CalculatorLocal;

public class CalculatorServlet extends HttpServlet {

    @EJB
    private CalculatorLocal calc = null;

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

        try {
            String firstNumber = req.getParameter("firstNumber");
            String secondNumber = req.getParameter("secondNumber");
            String operation = req.getParameter("operation");

            int firstInt = (firstNumber == null) ? 0 : Integer.valueOf(firstNumber).intValue();
            int secondInt = (secondNumber == null) ? 0 : Integer.valueOf(secondNumber).intValue();

            if ( "multiply".equals(operation) ) {
                req.setAttribute("result", calc.multiply(firstInt, secondInt));
            }
            else if ( "add".equals(operation) ) {
                req.setAttribute("result", calc.sum(firstInt, secondInt));
            }

            System.out.println("Result is " + req.getAttribute("result"));

            getServletContext().getRequestDispatcher("/sample-docu.jsp").forward(req, resp);

        }
        catch ( Exception e ) {
            e.printStackTrace();
            throw new ServletException(e);
        }
    }
}

Deployment Plans

The structure of the deployable should look like the following:

...