To enable Servlet, JSP, JSF etc to use a remote EJB, performing resource injection is essential. JSP however takes a different way to inject an EJB into it than that taken by the rest. let's see all of them by example.
In JSF, a remote EJB can be injected in a very simple way as can be seen in the following ManagedBean. An EJB may a stateful, a stateless or a singleton.
Suppose the interface which is implemented by the session bean is namely CustomerBeanRemote
@ManagedBean
@RequestScoped
public class AddSubscription
{
@EJB
private CustomerBeanRemote obj=null;
//Getters and setters.
}
Here the remoter EJB can be injected only with one annotation @EJB just before the interface declaration. Since EJB is injected here, the interface is able to call the methods in the session bean even if it is explicitly assigned null. null here makes no sense at all.
Servlet takes the same view as shown below.
public class Add extends HttpServlet {
{
@EJB
private CustomerBeanRemote obj=null;
//Rest of the elegant Servlet code goes here.
}
JSP (and JSTL/EL) however takes a different view as mentioned below.
try
{
obj=(CustomerBeanRemote )new
InitialContext().lookup(CustomerBeanRemote.class.getName());
}
catch(NamingException e)
{
out.println(e.getMessage());
}
obj.someEJBMethod();
or
try
{
obj=(CustomerBeanRemote )new
InitialContext().lookup("Specific JNDI");
}
catch(NamingException e)
{
out.println(e.getMessage());
}
obj.someEJBMethod();
Why JSP (or JSTL/EL) requires a JNDI (Java Naming and Directory Interface) to perform a resource injection while in Servlet and JSF it can simply be performed with only one annotation which is @EJB?