Skip navigation

Tag Archives: EJB3

I use Glassfish for application server. Here is the EJB:

package ejb3.bean;
import javax.ejb.Remote;

public interface HelloEjb {                                        
    String printHello(String name);


package ejb3.bean;
import javax.ejb.Stateless;

@Stateless( name="HelloEjb")
public class HelloEjbBean implements HelloEjb {
    public HelloEjbBean() {}

    public String printHello(String name) {
        return "Hello bro " + name + " welcome to EJB 3";

Package it as JAR or EAR, start Glassfish( GLASSFISH_HOME/bin/asadmin start-domain DOMAIN_NAME ) then use Admin Console (default: http://localhost:4848 ) to deploy the EJB.

To call the EJB from servlet we can directly use @EJB annotations, to get the instance of the EJB. In below sample i send the EJB to JSP page:

package ejb3.servlet;

import ejb3.bean.HelloEjb;

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

public class HelloEjb3Servlet extends HttpServlet {
    private HelloEjb helloEjb;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
		execute(request, response);

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
		execute(request, response);

	private void execute(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
        	request.setAttribute("helloEjb", helloEjb);
        	request.setAttribute("printHello", helloEjb.printHello("Djunaedi"));
        	request.getRequestDispatcher("/HelloEjb3.jsp").forward(request, response);                            

To get EJB instance in JSP using @EJB (inside scriplets) isn’t working, i get null instance. So i use JNDI lookup and that’s work:

<%@ page import="ejb3.bean.HelloEjb" %>
<%@ page import="javax.naming.InitialContext" %>
<%@ page import="javax.naming.Context" %>
<head><title>Hello EJB 3 !</title></head>
HelloEjb helloEjb;
try {
Context context = new InitialContext();
helloEjb = (HelloEjb) context.lookup(HelloEjb.class.getName());
catch(Exception e) {
// exception code here
Object HelloEjb Directly : <%= helloEjb %><br>
Print Hello : <%= helloEjb.printHello("Ujang") %>

Object HeloEjb from Servlet : <%= request.getAttribute("helloEjb") %><br>
Print Hello : <%= request.getAttribute("printHello") %>

Calling EJB 3 using JNDI lookup isn’t the same between Application Server, JNDI lookup name is not standardized. Refer to this article find out more.