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

别等时光非礼了梦想. 提交于 2019-11-28 23:30:42
ewernli

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.

The ServletContext represents the application scope. Application scoped attributes are shared among all requests in all sessions. It are "application wide globals". You don't want to store client (thus, session) specific information in there. If a new client logs in, the existing EJB in the application scope will be overridden with the client-specific one and be reflected to all clients.

The session scope is exactly for this purpose. Make use of it.

Just to clearify a bit: The ServletContext is initialized when a servlet is created (see Servlet Specs) and is unique to that very instance. A servlet uses multiple threads to handle concurrent client requests. The servlet container decides when to create or destroy servlets and delegates the client requests.

This is why you might end up having 1 servlet handling the request for n users (n >= 1) and thus in the above sample code using ServletContext every user would end up sharing the session bean of the user who caused creation of the servlet.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!