Accessing Enterprise Beans

Client gets access to enterprise beans using:

  • Dependency Injection using Java programming language annotations. Eg. Javax.ejb.EJB annotation.
  • JNDI lookup for application running outside JEE server-managed environment

EJB Example Using JNDI Lookup

CalculatorRemote.java File
package com.jtechies;

import javax.ejb.Remote;
@Remote
public interface CalculatorRemote {
 public float add(float x, float y);
 public float subtract(float x, float y);
 public float multiply(float x, float y);
 public float division(float x, float y);
} 
Calculator.java File
package com.jtechies;

import java.math.*;
import javax.ejb.Stateless;
import javax.ejb.Remote;  

@Stateless
public class Calculator implements CalculatorRemote{
  public float add(float x, float y){ 
  return x + y;
 }

 public float subtract(float x, float y){
  return x - y;
 }
  public float multiply(float x, float y){
  return x * y;
 }
 public float division(float x, float y){
 return x / y;
 }
}
Client.java File
package com.jtechies;

import java.io.IOException;
import java.io.PrintWriter;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Client
 */
@WebServlet("/Client")
public class Client extends HttpServlet {
	private static final long 
	serialVersionUID = 1L;
       
    public Client() {
        super();
    }

	protected void doGet
	(HttpServletRequest request, 
		HttpServletResponse response) 
		throws ServletException, 
		IOException{
		PrintWriter out = response.getWriter();
		CalculatorRemote calculator = null;
		Context context = null;
		try {
			context = new InitialContext();
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
		
			// Give the name of your 
			// interface follow with package name
			calculator = (CalculatorRemote) 
				context.lookup
				("com.jtechies.CalculatorRemote");
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.println("<html>");
		out.println("<head>");
		out.println(">title<
		Calculator</title>");
		out.println("<body>");
		out.println("<h3>Addition = 
		"+calculator.add(200, 100)+"</h3>");
		out.println("<h3>subtraction = 
		"+calculator.subtract(200, 100)+"</h3>");
		out.println("<h3>multiplication = 
		"+calculator.multiply(200, 100)+"</h3>");
		out.println("<h3>division = 
		"+calculator.division(200, 100)+"</h3>");
		out.println("</body>");
		out.println("</html>");
	}
}
Output

EJB JNDI Output