我正在學習EJB並編寫了一個使用GlassFish 4的示例程序,但由於某些原因,它無法正常工作。簡單單例EJB示例
的index.jsp:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="javax.ejb.EJB" %>
<%@ page import="ejbtest.utility.Utility" %>
<%@ page import="ejbtest.action.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>EJB Test</title>
</head>
<body>
<%
try {
Utility utility = new Utility();
out.println("count: " + utility.getCount() + "<br/><br/>");
Trigger1 trigger1 = new Trigger1();
out.println("trigger1 count: " + trigger1.getTriggerCount());
} catch (NullPointerException npe) {
out.println("Nullpointer caught");
}
%>
</body>
</html>
Utility.java:
package ejbtest.utility;
import javax.ejb.Singleton;
import javax.ejb.Startup;
@Startup
@Singleton
public class Utility {
int count;
public Utility() throws NullPointerException {
count = 0;
count++;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
Trigger1.java:
package ejbtest.action;
import ejbtest.utility.Utility;
import javax.faces.bean.ApplicationScoped;
import javax.inject.Inject;
@ApplicationScoped
public class Trigger1 {
@Inject
Utility utility;
public Integer getTriggerCount() {
return utility.getCount();
}
}
不希望輸出:
數:1
空指針抓住
我在Tomcat 7和GlassFish 4內部作爲JSP scriptlet而不是主要類嘗試了它,但我得到了同樣的結果。 .. – ThreaT
顯示scriplet代碼。如果你這樣做新的Trigger1(),所以它是錯誤的。由您自己創建的對象會創建外部EJB容器並忽略EJB註釋。您的Trigger1對象必須由EJB容器創建。 – Fireworks
代碼已更新,仍然通過JSP獲得NullPointerException – ThreaT