I use Glassfish for application server. Here is the EJB:
(interface)
package ejb3.bean; import javax.ejb.Remote; @Remote public interface HelloEjb { String printHello(String name); }
(implementation)
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; import java.io.IOException; public class HelloEjb3Servlet extends HttpServlet { @EJB 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" %> <html> <head><title>Hello EJB 3 !</title></head> <body> <%! HelloEjb helloEjb; %> <% try { Context context = new InitialContext(); helloEjb = (HelloEjb) context.lookup(HelloEjb.class.getName()); } catch(Exception e) { // exception code here } %> <p> Object HelloEjb Directly : <%= helloEjb %><br> Print Hello : <%= helloEjb.printHello("Ujang") %> <p> Object HeloEjb from Servlet : <%= request.getAttribute("helloEjb") %><br> Print Hello : <%= request.getAttribute("printHello") %> </body> </html>
notes:
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.
References:
– http://www.adam-bien.com/roller/abien/entry/ejb_3_portability_issue_why
– http://javahowto.blogspot.com/2006/09/default-jndi-name-for-resource-or-ejb.html
– https://glassfish.dev.java.net/javaee5/ejb/EJB_FAQ.html