EJB - Simple Adder

First posted 26/03/2012

Small recap of what I did in the tutorial session for EJB.
This application will take two integers and add them together using Enterprise Java Beans web application client.
I'm using Netbeans 7.1 to run this program.

Creating a Java Class

  1. New Java Application Project
  2. Name it "AdderLib" for the library
  3. Untick the create main class
  4. Create a new package named "mysession"
  5. Create new java class inside the package and name it "testRemote"

Creating an EJB Module

  1. Create a new EJB Module project in Java EE named "AdderEJB"
  2. Create a new Session Bean named "AddSession" in package "mysession"
  3. Tick Session Type as Stateless
  4. Remote Interface and choose "AdderLib" in the dropdown list
  5. As you can see in the library, AdderLib.jar is being used as its remote interface.
  6. In AddSession.java, create a new method for business logic (right click > Insert code > add business logic)
  7. For example,
    public Double Add(double x, double y) {
            return x+y;
  8. It will automatically implement the method Add() inside remote interface (testRemote.java)
    Double Add(double x, double y); //inside AdderLib remote interface
  9. Build it first.

Creating a Web Application (JSF)

  1. Now create a new Java Web Application
  2. Create a class called "AdderBean" inside "bean" package
  3. Add @Stateless and @ManagedBean annotation and import all the required class
  4. Add @EJB annotation in the first line after the first curly bracket (lol?)
  5. Now put some variables up in this shit
    Double n1,n2,sum;
  6. Create the setter and getter (protip: right click > insert code > setter & getter)
  7. In order to use the previous EJB module, we need to import it;
    import mysession.test2Remote;
  8. and name the variable as "bean"
    test2Remote bean;
  9. Import both remote interface and EJB module into Web Application's Libraries
    - Libraries > Add Project... > "AdderEJB" and "AdderLib"
  10. All errors are gone.
  11. In Web Pages folder, add a new JSF page named "result.xhtml"; this will be our result page
  12. In the existing index.xhtml, put the following
    First: <h:inputText value="#{adderBean.n1}"/>
    Second: <h:inputText value="#{adderBean.n2}"/>
    <h:commandButton action="#{adderBean.doOk}" value="Add"/>
  13. All we need to do now is to make a new method in adderBean called "doOk"
    public String doOk() {
      sum = bean.Add(n1, n2);
      return "result";
  14. It should be okay since we have imported all the libraries inside our web application
  15. Use result.xhtml to output the sum result
    <h:outputText value="#{adderBean.sum}"/>

Download Source Code

Show Comments

Get the latest posts delivered right to your inbox.