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?
ServletContext
andHttpSession
are part of Servlet API, not JSP API. The root cause of your problem is exactly there in the Servlet API (actually, the ignorance of the Servlet API). – Conjuration