How to cancel a session in JSF 2.0?

What is the best way to cancel a session in a JSF 2.0 application? I know that JSF itself does not handle the 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 ServletAPI?
  • Consider a scenario in which @SessionScoped UserBean processes the user's login-logout. I have this method in the same bean. Now when I call the reset() method after I have finished with the necessary update database, what will happen to my current bean session? since even the bean itself is stored in an HttpSession ?
+54
session jsf-2 managed-bean session-scope
Apr 11 2018-11-11T00:
source share
2 answers

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

You can use ExternalContext#invalidateSession() to terminate the session without having 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 bean session? since even the bean itself is stored in an HttpSession?

It will still be available in the current response, but it will no longer be in the next request. Therefore, it is important that the redirect (new request) is triggered after cancellation, otherwise you are still showing data from the old session. Redirecting can be done by adding faces-redirect=true to the result, as I did in the above example. Another way to send a redirect is to use ExternalContext#redirect() .

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

In this context, its use is doubtful, since using navigation results is simpler.

+114
Apr 11 '11 at 11:25
source share
— -
 public void logout() { FacesContext.getCurrentInstance().getExternalContext().invalidateSession(); } 
+12
Jul 19 2018-12-12T00:
source share



All Articles