This tutorial will show you how to develop a Java EE Session Bean in Eclipse, and deploy it in on an application server.
Before you begin, you need to have have both the Java Development Kit (JDK) and an application server installed on localhost. In this example I used Glassfish, which has an autodeploy directory. When an EJB jar file is dropped into the autodeploy directory, the application server automatically deploys it. To download the JDK, click
here. To download Glassfish, click
here.
Step 1: Create new EJB projectLet Eclipse generate the EJB-deployment descriptor.
Include two Java EE jars (appserv-rt.jar and javaee.jar) which is needed to compile the beans. You can find the jars in the lib directory of your Glassfish installation directory. Add the jars to your project build path (Right-click on project, then click Build Path).
Step 3: Create the EJB Stateless Session BeanWhen you finish this step, you will find three skeleton class files of your bean. Make sure they look like the code examples below:
ExampleSessionBean source:
package example;
import javax.ejb.Stateless;
@Stateless(name = "ExampleSessionBean",
mappedName = "ejb/ExampleSessionBean")
public class ExampleSessionBean implements
ExampleSessionBeanRemote, ExampleSessionBeanLocal {
public ExampleSessionBean() {
;
}
public int multiply(int a, int b) {
return a * b;
}
public int add(int a, int b) {
return a + b;
}
public int substract(int a, int b) {
return a - b;
}
}
ExampleSessionBeanLocal source:
package example;
import javax.ejb.Local;
@Local
public interface ExampleSessionBeanLocal {
public int multiply(int a, int b);
public int add(int a, int b);
public int substract(int a, int b);
}
ExampleSessionBeanRemote source:
package example;
import javax.ejb.Remote;
@Remote
public interface ExampleSessionBeanRemote {
public int multiply(int a, int b);
public int add(int a, int b);
public int substract(int a, int b);
}
Step 7: Export project as EJB jarTo compile the EJB-jar file, we select the project and do a right-click. Now select Export and then EJB JAR file. Now fill in the next screens:
Step 8: Deploy the EJB-jarNow drag and drop the exported EJB-jar file to the autodeploy directory of Glassfish. The bean is now ready for use.
Step 9: Create remote test clientThe step described next is optional. In this step we create a test client, which is run within Eclipse to test the remote EJB interface we created.
import javax.naming.InitialContext;
import example.ExampleSessionBeanRemote;
public class Main {
public void runTest() throws Exception {
InitialContext ctx = new InitialContext();
ExampleSessionBeanRemote bean =
(ExampleSessionBeanRemote) ctx
.lookup("ejb/ExampleSessionBean");
int result = bean.multiply(3, 4);
System.out.println(result);
}
public static void main(String[] args) {
Main cli = new Main();
try {
cli.runTest();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Compile and run within Eclipse to view the result in the Console tab.