Java:跟踪用户登录会话 - 会话EJB与HTTPSession

bgu*_*uiz 13 java session servlets ejb stateful

如果我想使用我的Web应用程序跟踪每个客户端的会话状态,这是一个更好的选择 - 会话Bean还是HTTP会话 - 要使用?

使用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)

使用Session EJB:

在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)之间还有其他更微妙的区别.特别是这两个:

  1. 异常处理.如果EJB中的事务失败,则bean将失效并且不能再使用.这可能会使Web应用程序中的错误处理策略复杂化.
  2. 并发.无法同时访问同一个SFSB,因此您需要在Web层中同步该SFSB.同样,这可能使设计复杂化.

有关更多详细信息,请参阅此答案:使用Servlet正确使用SFSB

总结:HttpSession在你的情况下,我会建议采用这种方法并反对SFSB; 只有当它提供了一些你无法做到的东西时才使用SFSB,但事实HttpSession并非如此.

  • 究竟.会话范围正是为了这个目的.存储和跟踪客户特定信息. (2认同)