What is the best possible way to invalidate session within a JSF 2.0 application? I know JSF itself does not handle session. So far I could find
private void reset() {
HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
.getExternalContext().getSession(false);
session.invalidate();
}
- Is this method correct? Is there a way without touching the ServletAPI?
- Consider a scenario wherein a
@SessionScoped
UserBean handles the login-logout of a user. I have this method in the same bean. Now when I call thereset()
method after I'm done with necessary DB updates, what will happen to my current session scoped bean? since even the bean itself is stored inHttpSession
?
You can use
ExternalContext#invalidateSession()
to invalidate the session without the need to grab the Servlet API.It will still be accessible in the current response, but it will not be there anymore in the next request. Thus it's important that a redirect (a new request) is fired after invalidate, otherwise you're still displaying data from the old session. A redirect can be done by adding
faces-redirect=true
to the outcome, as I did in the above example. Another way of sending a redirect is usingExternalContext#redirect()
.Its use is however questionable in this context as using a navigation outcome is simpler.