【发布时间】:2012-02-11 19:33:42
【问题描述】:
我正在使用 JSF、PrimeFaces、Glassfish 和 Netbeans 构建我的第一个 Java EE 应用程序。因为我是新手,所以我可能错误地处理了核心问题。
核心问题:我想安全地维护用户的信息。关于是否应该在 JSF 会话 bean 或有状态会话 EJB 中维护它似乎存在冲突的想法。我正在尝试使用有状态会话 EJB,因为这样更安全。
问题是我的应用程序似乎正在创建该 bean 的多个实例,而我希望它创建一个并重新使用它。如果我刷新页面,它将运行@PostConstruct 和@PostActivate 3 次,它们都具有不同的实例。然后,当我重新部署应用程序时,它们都会被销毁。
我是否误解了它应该如何工作或配置错误?
我将尝试展示一个精简的代码示例:
basic.xhtml:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
Hello from Facelets
<c:if test="#{loginController.authenticated}">
Authenticated
</c:if>
<c:if test="#{loginController.authenticated}">
Authenticated
</c:if>
<c:if test="#{loginController.authenticated}">
Authenticated
</c:if>
</h:body>
</html>
LoginController:
@Named(value = "loginController")
@RequestScoped
public class LoginController implements Serializable {
@EJB
private UserBeanLocal userBean;
public boolean isAuthenticated() {
return userBean.isAuthenticated();
}
}
UserBean(不包括UserBeanLocal接口)
@Stateful
public class UserBean implements UserBeanLocal, Serializable {
boolean authenticated = false;
@PostConstruct
@PostActivate
public void setup(){
System.out.println("##### Create user Bean: "+this.toString());
}
@Override
public boolean isAuthenticated() {
System.out.println("########## Authentication test is automatically passing.");
authenticated = true;//hard coded for simplicity.
return authenticated;
}
@PrePassivate
@PreDestroy
public void cleanup(){
System.out.println("##### Destroy user Bean");
}
}
最后,这是刷新 3 次后 Glassfish 的输出:
INFO: ##### Create user Bean: boundary._UserBean_Serializable@2e644784
INFO: ########## Authentication test is automatically passing.
INFO: ########## Authentication test is automatically passing.
INFO: ########## Authentication test is automatically passing.
INFO: ##### Create user Bean: boundary._UserBean_Serializable@691ae9e7
INFO: ########## Authentication test is automatically passing.
INFO: ########## Authentication test is automatically passing.
INFO: ########## Authentication test is automatically passing.
INFO: ##### Create user Bean: boundary._UserBean_Serializable@391115ac
INFO: ########## Authentication test is automatically passing.
INFO: ########## Authentication test is automatically passing.
INFO: ########## Authentication test is automatically passing.
【问题讨论】:
-
虽然这很旧(并且得到了很好的回答),但我认为值得一提的是,“当 [您] 重新部署应用程序时它们都会被销毁”的原因是因为当您注入有状态会话时bean 使用@EJB 由应用程序触发@PreDestroy VIA a @Remove 方法,否则它只是挂起。这就是为什么你的输出永远不会达到
cleanup()的原因。另请参阅 this demo/test app 了解一些 @EJB 与 CDI @Inject 生命周期案例。 -
对不起:错字test app here。
标签: jakarta-ee jsf-2 ejb-3.0