使用Netbeans开发JavaEE应用程序。实体管理器在应用程序中获取空值。他们没有被注射。 仍然会得到一个nullPointerException,因为em在createNamedQuery中得到一个空值。 谁能告诉我我错过了什么。
JSP page-index.jsp:
<%@page import="managed.userBean" %>
<jsp:useBean id="bean" class="managed.userBean" scope="session" />
.....
<input type="submit" value="Submit" onclick="<jsp:scriptlet> bean.validate();</jsp:scriptlet>" />
userBean.java
package managed;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import session.UserFacade;
@ManagedBean
@SessionScoped
public class userBean implements Serializable {
private String uid, password,role,fname,lname;
private String response="" ;
@EJB
UserFacade userFacade;
....
public String validate() {
System.out.println("in validate going to user facade: " + uid + password);
response = userFacade.validateUser(uid,password);
.....
}
UserFacade.java
package session;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Stateless
public class UserFacade extends AbstractFacade<User> {
@PersistenceContext (unitName = "ExamSysPU")
public EntityManager em;
String role;
@Override
protected EntityManager getEntityManager() {
System.out.println("check if em is open");
return em;
}
public UserFacade() {
super(User.class);
}
public String validateUser(String uid, String password) {
...
List results = em.createNamedQuery("User.findByUid").setParameter("uid", uid).getResultList();
....
}
的persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="ExamSysPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>test</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
谢谢, 希尔帕
答案 0 :(得分:2)
您的问题是由于您使用UserBean
手动创建<jsp:useBean>
而不是使用由JSF创建和管理的那个(因此为您自动注入了所有必需的依赖项)。基本上,如果您手动创建和管理bean,那么您还应该手动创建,管理和注入其依赖项。
停止阅读那些已有十年历史的JSP 1.x教程。它们不再适用于这些Java EE 6天了,现在只会让您对正确的方法感到困惑。 JSP已经被Facelets(XHTML)取代。完成一些JSF2 / Facelets教程。基本上,您可以通过至少包含以下内容的Facelets文件替换JSP文件来解决您的具体问题:
<h:form>
<h:commandButton value="Submit" action="#{bean.validate}" />
</h:form>