Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

session.invalidate() doesn't actually clears JSF session scoped values

Tags:

session

jsf

I am seeing a similar issue as mentioned in this question - https://stackoverflow.com/questions/1495390/how-do-i-invalidate-a-session-in-jsf.

I have a session scoped LoginBean, which have an action logout as #

    ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
    HttpSession session = (HttpSession) ec.getSession(false);
    HttpServletResponse response = (HttpServletResponse) ec.getResponse();

    // remove cookies
    response.addCookie(facade.removeCookie(((HttpServletRequest)ec.getRequest()).getCookies()));
    // check what we have in sessionMap
    System.out.println(ec.getSessionMap());
    // remove attribute
    session.removeAttribute("XYZ");

    // invalidate session
    if (session != null) {
        System.out.println("invalidating session");
        session.invalidate();
    }
    // see what is there in session map
    System.out.println(ec.getSessionMap());

It almost work fine.

Output #

{xyzBean=com.xyz.bean.XYZBean@46f046f0,... }
invalidating session
{}

The sessionMap being empty, means there are no session scope beans. However, after logout action it redirects to another same page. Login being a layer on same page. I see that fragment jsps still have showing old data.

I am not removing JSESSIONID in facade.removeCookie. It removes some other cookies related to user.

Any help would be appreciated.

Thanks.

like image 977
bahetivijay Avatar asked Dec 28 '25 01:12

bahetivijay


1 Answers

You're likely viewing a page which is been served from browser cache. You need to add HTTP response headers which instructs the webbrowser to not cache the dynamic pages. You can do this with a javax.servlet.Filter which is mapped on an <url-pattern> of interest, e.g. *.jsf or something and does the following job in doFilter() method:

HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Cache-Control", "no-cache,no-store,must-revalidate"); // HTTP 1.1
httpResponse.setHeader("Pragma", "no-cache"); // HTTP 1.0
httpResponse.setDateHeader("Expires", 0); // Proxies.
chain.doFilter(request, response);

Don't forget to clear the browser cache before testing ;)


Unrelated to the problem, the if (session != null) nullcheck in your code is superfluous since session can never be null when it reaches that nullcheck. If it was null, it would have thrown a NullPointerException at the removeAttribute() call and thus never reach the nullcheck.

like image 141
BalusC Avatar answered Dec 30 '25 18:12

BalusC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!