2 Replies Latest reply on Oct 5, 2005 11:36 PM by andrigtmiller

    Inject an EJB3 in a servlet

    gmichalk

      Hi,

      if have a stateless session bean which works OK when injected in another session bean within the same container.

      I have tried the same in a servlet:

      public class MyServlet....

      ....
      @EJB MyBean bean
      public void doPost(....
      {
      Collection k = bean.getCollection();
      }

      The servlet always crashes on this very line. How can this be done ? After googeling, I have read that this was more of a tomcat issue. But it would be definitely nice ;-)

      I also checked the TrailBlazer's DVD example, but could'nt find anything.


        • 1. Re: Inject an EJB3 in a servlet
          guilherme_82

          Hi,
          I do not have the solution to your problem, instead, I have another question.
          I am trying to do that, but accessing the Session Bean from an Action of Struts which would be equivalent of accessing from a servlet. . I want know how do you instantiate your Bean. Don't you use JNDI? Or do you instantiate it with new... ?
          when I use:

          @Stateful
          public class MyBean implements RemoteBean{
          }

          @Remote
          public interface RemoteBean{
          }

          public class MyApp{

          public void init(){
          InitialContext context = new InitialContext();
          String lookup = RemoteBean.class.getName();
          RemoteBean bean = (RemoteBean) context.lookup(lookup);
          bean.method();
          }
          }

          when I execute the line bean.method I get the exception:

          java.lang.NoSuchMethodError: org.jboss.aop.joinpoint.MethodInvocation.([Lorg/jboss/aop/advice/Interceptor;JLjava/lang/reflect/Method;Ljava/lang/reflect/Method;Lorg/jboss/aop/Advisor;)V

          Do you what's wrong in my code?

          Thanks, Guilherme

          • 2. Re: Inject an EJB3 in a servlet
            andrigtmiller

            As far as I know you cannot use dependency injection in a servlet. In the init method of the servlet you stil have to do a JNDI lookup. Only the JNDI lookup doesn't have to use the URL of old, but can be as follows:

            
             private MyBean bean = null;
            
            public void init(ServletConfig config) throws ServletException
            
             super.init(config);
            
             InitialContext context = null;
            
             try {
             context = new InitialContext();
             bean = (MyBean) context.lookup(MyBean.class.getName());
             } catch(Exception lookupError) {
             throw new ServletException(lookupError);
             }
            
            


            This should fix your problem.