使用JavaEE处理基本Web应用程序。我已经创建了一个JavaBean,一个Bean接口,一个Servlet,一个实体和一个Jsp页面(如下所示)。当我请求servlet URL时,它会收到错误消息Error instantiating servlet class and the root cause is:
javax.naming.NameNotFoundException: Name [com.packageName.UserServlet/userDao] is not bound in this Context. Unable to find [com.packageName.UserServlet].
奇怪的是(在我看来)是当我删除UserServlet类中的@EJB注释时,它可以工作。我不明白为什么......
如果我只是删除了@EJB,那么在执行userDao.addUser(user)
(NullPointerException)时会出现问题,我认为这是因为我删除了@EJB?
我是JavaEE的初学者,所以我的术语可能有点不对,但我希望你理解我的问题。
类:UserServlet
@WebServlet(name = "UserServlet", urlPatterns = {"/UserServlet"})
public class UserServlet extends HttpServlet {
@EJB("UserDaoBean") <---- This annotation makes it crash
private UserDaoLocal userDao;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int userId = 2;
User user = new User(userId, "userName", "password");
userDao.addUser(user);
request.getRequestDispatcher("userinfo.jsp").forward(request, response);
}
课程:用户
@Entity
@Table
@NamedQueries(@NamedQuery(name = "User.getAll", query = "select e from User e"))
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column
private int userid;
@Column
private String name;
@Column
private String password;
public User() {
}
public User(int userid, String name, String password) {
this.userid = userid;
this.name = name;
this.password = password;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
类:UserDaoLocal
public interface UserDaoLocal {
void addUser(User user);
}
类:UserDaoBean
@Local
@Stateless(name = "UserDaoBean")
public class UserDaoBean implements UserDaoLocal {
@PersistenceContext
private EntityManager entityManager;
public UserDaoBean() {
}
@Override
public void addUser(User user) {
entityManager.persist(user);
}
}
答案 0 :(得分:1)
为什么在已有UserDaoBean
时使用@localbean
注释对interface view
进行注释,如果有@localbean
则应使用no- interface view
。用@local
注释注释接口,因为它表示bean的本地视图。似乎你给豆子命名了
@Stateless(name = "UserDaoBean")
public class UserDaoBean implements UserDaoLocal {}
因为你已经覆盖了你不能使用的默认类名
@EJB
使用@EJB(beanName="UserDaoBean")
private UserDaoLocal userDao;
或只删除name
stateless annotation
属性
@Stateless
public class UserDaoBean implements UserDaoLocal {}
并像这样进行ejb调用
@EJB
UserDaoLocal userbean
确保在运行之前清理并构建。
答案 1 :(得分:0)
@WebServlet
似乎不太自然。
在您的异常中,我们可以看到容器使用奇怪的JNDI名称来定位您的EJB实例:com.packageName.UserServlet/userDao
即使它是样板代码,您也可以尝试像过去那样绕过这个问题:在您的web.xml中声明您的EJB,例如:
<ejb-local-ref>
<ejb-ref-name>UserDaoBean</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<local>yourPackage.UserDaoBean</local>
</ejb-local-ref>