0
votes

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?

1

1 Answers

3
votes

A JSP is a servlet, so you should certainly be able to use the annotation in the JSP:

<%! @EJB private CustomerBeanRemote obj=null; %>

(untested though).

But even if it doesn't work, that's not a problem because JSPs should not contain Java code anyway. JSPs should be used to generate markup from beans prepared by a controller (Servlet or action of your preferred framework) written in Java.

See How to avoid Java code in JSP files?

Also, your snippets of code are wrong: they use the obj variable although a naming exception occurred when initializing them. This will obviously lead to a NullPointerException.