如果我想跟踪每个使用我的 Web 应用程序的客户端的对话状态,使用哪个是更好的选择 - session Bean 或 HTTP session ?
使用 HTTP session :
//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
使用 session EJB:
在WEB-INF/web.xml
中注册为Web Application Listener的ServletContextListener的实现:
//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);
...
在 JSP 中:
public void jspInit() {
UserState state = (UserState)(getServletContext().getAttribute("UserState"));
...
}
同一 JSP 主体中的其他地方:
String uid = state.getUID();
//now do things with the user id
在我看来,它们几乎相同,主要区别在于 UserState 实例在前者的 HttpRequest.HttpSession
中传输,而在 ServletContext 中传输
在后者的情况下。
这两种方法中哪种更稳健,为什么?
最佳答案
正如@BalusC 所指出的,在您的示例中,EJB 对于所有客户端都是相同的——而不是您想要的。
您仍然可以更改它并让每个客户端拥有一个 EJB,例如,如果您在用户登录时创建 EJB 并将其存储在 session 中,或类似的事情。
但是在使用 HttpSession
和有状态 session bean (SFSB) 之间还有其他更细微的区别。尤其是这两个:
- 异常处理。如果 EJB 中的事务失败,bean 将失效并且不能再使用。这会使 Web 应用程序中的错误处理策略复杂化。
- 并发。同一个SFSB不能并发访问,需要在web层同步。同样,这会使设计复杂化。
有关详细信息,请参阅此答案:Correct usage of SFSB with Servlets
总而言之:在您的情况下,我建议采用 HttpSession
方法并反对 SFSB;仅当 SFSB 提供了 HttpSession
无法提供的功能时才使用 SFSB,但事实并非如此。
关于Java:跟踪用户登录 session - session EJB 与 HTTPSession,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2808773/