我正在使用JSF,PrimeFaces,Glassfish和Netbeans构建我的第一个Java EE应用程序.因为我是新手,所以我可能会接近核心问题.
核心问题:我想安全地维护用户的信息.关于是否应该在JSF会话bean或有状态会话EJB中维护它似乎存在矛盾的想法.我正在尝试使用有状态会话EJB,因为它更安全.
问题是我的应用程序似乎正在创建该bean的多个实例,当我希望它创建一个并重新使用它时.如果我刷新页面它运行@PostConstruct和@PostActivate3次,他们都用不同的实例.然后,当我重新部署应用程序时,它们都会被破坏.
我误解了它应该如何工作或错误配置了什么?
我将尝试显示一个修剪过的代码示例:
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>
Run Code Online (Sandbox Code Playgroud)
LoginController:
@Named(value = "loginController")
@RequestScoped
public class LoginController implements Serializable {
@EJB
private UserBeanLocal userBean;
public boolean isAuthenticated() {
return userBean.isAuthenticated();
}
}
Run Code Online (Sandbox Code Playgroud)
UserBean(不包括UserBeanLocal界面)
@Stateful
public …Run Code Online (Sandbox Code Playgroud) 我是EJB的新手,我正在尝试理解Stateless和Stateful bean之间的差异,所以我做了一个简单的例子来测试它们.
@Stateless
public class Service {
private int num;
public Service(){
}
public int getNum() {
return num;
}
public void setNum() {
this.num++;
}
}
Run Code Online (Sandbox Code Playgroud)
@WebServlet("/Controller1")
public class Controller1 extends HttpServlet {
@EJB
private Service serv;
public Controller1() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
serv.setNum();
response.getWriter().println(serv.getNum());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Run Code Online (Sandbox Code Playgroud)
和有状态的等价物:
@Stateful
public class ServiceStateful implements Serializable{ …Run Code Online (Sandbox Code Playgroud)