Search code examples
jakarta-eejndi

What Context Name to use in JNDI Lookup?


I have a SFSB declared as such:

@Stateful(name="StatefulBean")
public class StatefulBean implements MyListener
{
    private String id;

    public StatefulBean()
    {
    }

    public void setId(String id)
    {
        this.id = id;
    }
}

I am trying to instantiate it in a servlet's doGet method like this:

protected void doGet(final HttpServletRequest request,
    final HttpServletResponse response) throws ServletException, IOException
{
    Date now = new Date();
    String id = new Long(now.getTime()).toString();

    try
    {
        Context context = new InitialContext();
        StatefulBean statefulBean = (StatefulBean) context.lookup("name");
        statefulBean.setId(id);
        response.getWriter().write("Created StatefulBean with id " + id);
    }
    catch(Exception ex)
    {
        response.getWriter().write("Exception creating bean:" + ex.getMessage());
    }
}

Both the servlet and the bean belong to my.package and are deployed in the same war file called BeanTest.war to a Glassfish3 server.

I'm having issues determing what name should be. The Glassfish server.log states that:

[#|2014-05-20T16:31:51.720-0600|INFO|glassfish3.1.2|javax.enterprise.system.container.ejb.com.sun.ejb.containers|_ThreadID=988;_ThreadName=Thread-14;|EJB5181:Portable JNDI names for EJB StatefulBean: [java:global/BeanTest/StatefulBean!my.package.MyListener, java:global/BeanTest/StatefulBean]|#]

I have tried setting name in the lookup call to both java:global/BeanTest/StatefulBean!ca.shaw.tno.oss.MyListener and java:global/BeanTest/StatefulBean. When the doGet is called with either, I get this error:

Exception processing batch:com.sun.proxy.$Proxy353 cannot be cast to my.package.StatefulBean

Since those are the only two naming options given by the Glassfish server, what am I supposed to use?


Solution

  • The issue is that I didn't have my StatefulBean annotated with @LocalBean. Once I added that, the JNDI lookup succeeded.

    @Stateful(name="StatefulBean")
    @LocalBean
    public class StatefulBean implements MyListener
    {
        private String id;
    
        public StatefulBean()
        {
        }
    
        public void setId(String id)
        {
            this.id = id;
        }
    }