Session Bean Tutorial

Introduction

This page provides Java source code and sample XML deployment descriptors for a J2EE 1.4 Session Bean.

Writing the Session Bean

We will need to produce the following artifacts and package them into a jar file:

Remote Interface

package com.codesuccess.tutorial.ejb;

import javax.ejb.EJBObject;
import java.rmi.RemoteException;

public interface Calculator extends EJBObject {
    int add(int aint bthrows RemoteException;
}

Home Interface

package com.codesuccess.tutorial.ejb;

import javax.ejb.EJBHome;
import javax.ejb.CreateException;
import java.rmi.RemoteException;

public interface CalculatorHome extends EJBHome {
    Calculator create() throws CreateExceptionRemoteException;
}

Bean Implementation

package com.codesuccess.tutorial.ejb;

import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.EJBException;
import java.rmi.RemoteException;

public class CalculatorBean implements SessionBean {

    public int add(int aint bthrows RemoteException {
        return a+b;
    }

    public void setSessionContext(SessionContext sessionContext)
        throws EJBExceptionRemoteException {
    }

    public void ejbCreate() throws EJBExceptionRemoteException {
    }

    public void ejbRemove() throws EJBExceptionRemoteException {
    }

    public void ejbActivate() throws EJBExceptionRemoteException {
    }

    public void ejbPassivate() throws EJBExceptionRemoteException {
    }
}

ejb-jar.xml

<?xml version="1.0"?>

<ejb-jar xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
                        http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd"
    version="2.1">

    <enterprise-beans>

        <session>
            <display-name>Calculator (Stateless Session Bean)</display-name>
            <ejb-name>Calculator</ejb-name>
            <home>com.codesuccess.tutorial.ejb.CalculatorHome</home>
            <remote>com.codesuccess.tutorial.ejb.Calculator</remote>
            <ejb-class>com.codesuccess.tutorial.ejb.CalculatorBean</ejb-class>
            <session-type>Stateless</session-type>
            <transaction-type>Container</transaction-type>
        </session>

    </enterprise-beans>
    <assembly-descriptor></assembly-descriptor>
</ejb-jar>