我正在尝试从数据库填充selectOneMenu
,我得到运行时错误Can't instantiate class
。我得到了
java.lang.NullPointerException at pointControllerConverter.getPoints(pointControllerConverter.java:89)
有什么建议吗?
这是我的代码:
xhtml文件:
<p:selectOneMenu id="point" value="#{pointController.selectedPoint}"
var="items_var">
<f:selectItems value="#{pointController.points}" var="points_var"
itemLabel="#{points_var.name}" itemValue="#{points_var.name}"/>
</p:selectOneMenu>
管理bean:
@ManagedBean(name = "pointController")
@SessionScoped
public class PointController implements Serializable {
@EJB
private ethoam.entity.PointFacade ejbFacade;
private List<point> points;
private point selectedPoint;
private point[] selectedPoints;
private List<Point> selectedPointsList;
private SelectItem[] PointNamesOptions;
public PointController() {
this.initList();
}
@PostConstruct
private void initList() {
points = new ArrayList<point>(PointControllerConverter.getPoints().values());
}
// getters setters
}
转换器类:
public static class PointControllerConverter implements Converter {
@PersistenceContext(unitName = "PointPU")
private static EntityManager ejbfacade;
public static Map<String, point> points = new HashMap<String, point>();
public static Map<String,point> getPoints() {
points = (Map<String, point>) ejbfacade.createNamedQuery("SELECT d FROM point d WHERE d.name = :name");
return points;
}
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
PointController controller = (PointController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "pointController");
return controller.ejbFacade.find(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof point) {
point o = (point) object;
return getStringKey(o.getIdPoint());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Point.class.getName());
}
}
}
答案 0 :(得分:0)
首先,我不知道你为什么使用转换器作为列表供应商!
您可能需要将getPoints()
逻辑移动到ManagedBean。
另一方面,NullPointerException是由于实体管理器注入失败引起的(我不知道为什么它是静态的)。
在转换器或验证器中,您无法使用@PersistenceContext或@EJB
进行注入请参阅原因: How to inject @EJB, @PersistenceContext, @Inject, @Autowired, etc in @FacesConverter?
你可以这样做:
Context envCtx = InitialContext().lookup("java:comp/env");
EntityManager em = (EntityManager) envCtx.lookup("persistence/PointPU");