bgu*_*uiz 13 java session servlets ejb stateful
如果我想使用我的Web应用程序跟踪每个客户端的会话状态,这是一个更好的选择 - 会话Bean还是HTTP会话 - 要使用?
//request is a variable of the class javax.servlet.http.HttpServletRequest
//UserState is a POJO
HttpSession session = request.getSession(true);
UserState state = (UserState)(session.getAttribute("UserState"));
if (state == null) { //create default value .. }
String uid = state.getUID();
//now do things with the user id
Run Code Online (Sandbox Code Playgroud)
在ServletContextListener的实现中注册为Web应用程序监听器WEB-INF/web.xml:
//UserState NOT a POJO this this time, it is
//the interface of the UserStateBean Stateful Session EJB
@EJB
private UserState userStateBean;
public void contextInitialized(ServletContextEvent sce) {
ServletContext servletContext = sce.getServletContext();
servletContext.setAttribute("UserState", userStateBean);
...
Run Code Online (Sandbox Code Playgroud)
在JSP中:
public void jspInit() {
UserState state = (UserState)(getServletContext().getAttribute("UserState"));
...
}
Run Code Online (Sandbox Code Playgroud)
在同一个JSP的主体的其他地方:
String uid = state.getUID();
//now do things with the user id
Run Code Online (Sandbox Code Playgroud)
在我看来,它们几乎相同,主要区别在于UserState实例HttpRequest.HttpSession在前者中传输,而在ServletContext后者的情况下传输.
这两种方法中哪一种更强大,为什么?
ewe*_*nli 11
正如@BalusC所指出的那样,在您的示例中,EJB对于所有客户端都是相同的 - 而不是您想要的.
您仍然可以更改它并在每个客户端拥有一个EJB,例如,如果您在用户登录并将其存储在会话中时创建EJB,或类似的东西.
但是使用HttpSession和有状态会话bean(SFSB)之间还有其他更微妙的区别.特别是这两个:
有关更多详细信息,请参阅此答案:使用Servlet正确使用SFSB
总结:HttpSession在你的情况下,我会建议采用这种方法并反对SFSB; 只有当它提供了一些你无法做到的东西时才使用SFSB,但事实HttpSession并非如此.