Is it thread unsafe for the @SessionScoped bean to maintain a reference to its HttpSession?

Taking a look at the unrelated part of this answer with another question , although I understand why the request and response links are threadunsafe in the example question, why is it useless for the SessionScoped bean to referencing the HttpSession it is associated with?

@SessionScoped
public class SessionManager {
    HttpSession session = null;
    ...
    @PostConstruct void initialize() {
        this.session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
    }

    private void onLogin(@Observes @LoggedIn User user) {

        // (1) housekeeping stuff

        // (2) destroy older, duplicate login session, if user did not previously 
        //     logout, in which case it would be really handy to have a reference
        //     to HttpSession. 

    }
}

      

+3


source to share


1 answer


While implementing the above example (see OP) I realized that keeping the session reference is not good because it is really insecure. This is smelly code.

I was surprised to see that not only was the old session invalid, but the current session was also destroyed by the container! Thus, the user exited the browser. Later I came across this Websphere best practices documentation which, although I am not using Websphere, helped me realize that session caching is not a good practice:



Don't try to save and reuse the HttpSession object outside of every servlet or JSP file.

The HttpSession object is an HttpRequest function (you can only get it through the req.getSession method) and its copy is only valid for the lifetime of the servlet method or JSP file. You cannot cache and reference the HttpSession object outside of the scope of the servlet or JSP file.

No need to cache the HttpSession; it is possible to cache the session id instead, and when a duplicate session is found, just add the previous duplicate session id to Set<String> invalidatedLoginSessionIds.

. Then refactor your application so that immediately upon receiving a request from the old session, invalidate the old session and redirect the old browser to the appropriate dummy. If no such request is received, the old session will simply crash and be destroyed anyway, so don't worry.

+2


source







All Articles