Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Tracking a user login session - Session EJBs vs HTTPSession

If I want to keep track of a conversational state with each client using my web application, which is the better alternative - a Session Bean or a HTTP Session - to use?

Using 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

Using Session EJB:

In the implementation of ServletContextListener registered as a Web Application Listener in 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);
    ...

In a JSP:

public void jspInit() {
    UserState state = (UserState)(getServletContext().getAttribute("UserState"));
    ...
}

Elsewhere in the body of the same JSP:

String uid = state.getUID();
//now do things with the user id

It seems to me that the they are almost the same, with the main difference being that the UserState instance is being transported in the HttpRequest.HttpSession in the former, and in a ServletContext in the case of the latter.

Which of the two methods is more robust, and why?

like image 791
bguiz Avatar asked May 11 '10 07:05

bguiz


1 Answers

As @BalusC pointed out, in your example the EJB would be the same for all clients -- not what you want.

You can still change that and have one EJB per client, if for instance you create the EJB when the user logs in and store it in the session, or something similar.

But there are other more subtle differences between using the HttpSession and a stateful session bean (SFSB). Especially these two ones:

  1. Exception handling. If a transaction fails in the EJB, the bean is invalidated and can not be used any longer. This can complicate the error handling strategy in the web application.
  2. Concurrency. The same SFSB can not be accessed concurrently, so you will need to synchronize that in the web layer. Again, this can complicate the design.

See this answer for more details: Correct usage of SFSB with Servlets

In summary: I would advise going for the HttpSession approach and against the SFSB in your case; use SFSB only if it provides something you can't do with HttpSession, which isn't the case.

like image 67
ewernli Avatar answered Oct 12 '22 03:10

ewernli