[ACCEPTED]-How to invalidate session in JSF 2.0?-session-scope

Accepted answer
Score: 125

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

You can use ExternalContext#invalidateSession() to invalidate the session without 11 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 10 still be accessible in the current response, but 9 it will not be there anymore in the next 8 request. Thus it's important that a redirect 7 (a new request) is fired after invalidate, otherwise 6 you're still displaying data from the old 5 session. A redirect can be done by adding 4 faces-redirect=true to the outcome, as I did in the above example. Another 3 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 2 use is however questionable in this context 1 as using a navigation outcome is simpler.

Score: 13
public void logout() {
    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
}

0

More Related questions