title: How to conduct a lookup of an EJB from a servlet context?
body: <p>I have a POJO that was instantiated from a servlet. I need to make a lookup of an EJB within this POJO, either CDI or JNDI. My JEE container is TomEE 1.6.0.</p>
  
  <p>My question is this: need the EJB have remote interface? Because if I instantiate it directly from the servlet by @EJB the remote interface does not need...</p>
  
  <p>Just see this simple example which always throws NameNotFoundException.</p>
  
  <pre><code>@Stateless
  public class MyEJB
  {
      public String sayHello()
      {
          return "Hello";
      }
  }
  </code></pre>
  
  <p>The next servlet try yo lookup MyEJB:</p>
  
  <pre><code>@WebServlet("/myServlet")
  public class MyServlet extends HttpServlet
  {
      private static final long serialVersionUID=1L;
  
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
      {
          try
          {
              Context ctx = new InitialContext();
              MyEJB ejb = (MyEJB) ctx.lookup("MyEJB");
  
              System.out.println(ejb.sayHello());            
          }
          catch(Exception ex)
          {
              ex.printStackTrace();
              throw new RuntimeException(ex);
          }
      }
  }
  </code></pre>
  
  <p>The line: <code>MyEJB ejb = (MyEJB) ctx.lookup("MyEJB");</code> always throws NameNotFoundException. But if I use @EJB it work fine. But I need do the lookup in JNDI mode because finally I will instantiate this EJB within a POJO.</p>
  
  <p>So, why fails this lookup ? </p>