如何将EJB注入servlet?

时间:2017-01-21 09:49:04

标签: java intellij-idea ejb tomcat7 java-ee-7

我是EJB和Java EE的新手。我试图用Tomcat 7在IntellijIDEA中创建我的第一个无状态EJB。我在Yakov Fein的Java教程中这样做,但是他在Eclipse \ GlassFish中做到了。所以我试图像

那样查找我的bean
Context ctx = new InitialContext();
HelloWorldBean myBean = (HelloWorldBean) ctx.lookup("java:app/com.practicaljava.lesson32.ejb/HelloWorldBean");

另一种我试图通过@EJB注释注入它的方式

@EJB HelloWorldBean myBean;

但是没有两种方式都没有工作

import com.practicaljava.lesson32.ejb.HelloWorldBean;

我没有在web.xml或其他具有相同设置的xml中进行EJB的任何映射或设置,因为它们根本不存在于该教程中。

servlet看起来像这样

@WebServlet("/HelloWorldServlet")
public class HelloWorldServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    //@EJB HelloWorldBean myBean;
    /**
     * @see javax.servlet.http.HttpServlet#HttpServlet()
     */
    public HelloWorldServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
     */
    @EJB HelloWorldBean myBean;
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        // TODO Auto-generated method stub
        try{

        //Context ctx = new InitialContext();
        //HelloWorldBean myBean = (HelloWorldBean) ctx.lookup("java:app/com.practicaljava.lesson32.ejb/HelloWorldBean");

        PrintWriter out = response.getWriter();
       out.println("Now, it's time for dependency injection demo: " + myBean.sayHello());

        }catch (Exception e ) {
            e.getStackTrace();
        }
    }

我试图添加一些库,制作配置,但每次都

javax.naming.NameNotFoundException: Name [com.practicaljava.lesson32.client.HelloWorldServlet/myBean] is not bound in this Context. Unable to find [com.practicaljava.lesson32.client.HelloWorldServlet].

0 个答案:

没有答案