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?
//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
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?
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:
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.