Java:跟踪用户登录会话 - 会话 EJB 与 HTTPSession
如果我想使用我的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
使用会话 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);
...
在 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
这两种方法中哪一种更健壮,为什么?