Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invalidate session in JSF 2.0?

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(); } 
  1. Is this method correct? Is there a way without touching the ServletAPI?
  2. 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 the reset() 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 in HttpSession?
like image 928
Niks Avatar asked Apr 11 '11 10:04

Niks


People also ask

Can we invalidate a session?

Correct Option: CWe can invalidate session by calling session. invalidate() to destroy the session.

How do I know if a session is invalidated?

Try passing false as the parameter to the getSession(boolean) . This will give back a session if it exists or else it will return null . HttpSession session = request. getSession(false); if (session == null || !

What is session in JSF?

The session scope allows you to create and bind objects to a session. It gets created upon the first HTTP request involving this bean in the session and gets destroyed when the HTTP session is invalidated. The request scope is present in JSF and CDI and functions in the same way.


1 Answers

Firstly, is this method correct? Is there a way without touching the ServletAPI?

You can use ExternalContext#invalidateSession() to invalidate the session without the need to grab the Servlet API.

@ManagedBean @SessionScoped public class UserManager {      private User current;      public String logout() {         FacesContext.getCurrentInstance().getExternalContext().invalidateSession();         return "/home.xhtml?faces-redirect=true";     }      // ...  } 

what will happen to my current session scoped bean? since even the bean itself is stored in HttpSession?

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 using ExternalContext#redirect().

public void logout() throws IOException {     ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();     ec.invalidateSession();     ec.redirect(ec.getRequestContextPath() + "/home.xhtml"); } 

Its use is however questionable in this context as using a navigation outcome is simpler.

like image 134
BalusC Avatar answered Oct 03 '22 17:10

BalusC