How to Access an EJB
If you run your servlet in a EJB 3.x capable container, accessing EJBs from a servlet is very easy. Similar to the @Resource annotation, you only need to declare a field or property with the EJB interface as type and an @EJB annotation. The container will automatically inject the value after the servlet's construction. Filters and listeners are also suported.
Let's take this simple EJB interface:
import javax.ejb.Local;
@Local
public interface HelloBeanLocal {
String hello();
}
The following servlet uses the @EJB annotation to acquire a reference to a HelloBeanLocal bean and invokes it in its doGet method:
import javax.ejb.EJB;
import javax.servlet.http.*;
import java.io.*;
public class EjbUsingServlet extends HttpServlet {
@EJB
private HelloBeanLocal helloBean;
private void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/plain; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
String v = helloBean.hello(); // invoke the EJB
response.getWriter().println("The EJB says " + v);
}
}

