How to invalidate session in JSF 2.0?

那年仲夏 提交于 2019-11-26 00:58:50

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.

Stani
public void logout() {
    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!