首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在JSF2.0中使会话失效?

如何在JSF2.0中使会话失效?
EN

Stack Overflow用户
提问于 2011-04-11 18:14:39
回答 3查看 88.9K关注 0票数 62

在JSF2.0应用程序中使会话失效的最佳方法是什么?我知道JSF本身并不处理会话。到目前为止我能找到

private void reset() {
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
            .getExternalContext().getSession(false);
    session.invalidate();
}

  1. 这个方法正确吗?有没有一种不接触ServletAPI?
  2. Consider的方法,在这种情况下,@SessionScoped UserBean处理用户的登录-注销。我在同一个bean中也有这个方法。现在,当我在完成必要的DB更新后调用reset()方法时,我当前的会话作用域bean将发生什么情况?因为即使是bean本身也存储在HttpSession

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-04-11 19:25:54

首先,这个方法正确吗?有没有一种不接触ServletAPI的方法?

您可以使用ExternalContext#invalidateSession()来使会话无效,而不需要获取Servlet API。

@ManagedBean
@SessionScoped
public class UserManager {

    private User current;

    public String logout() {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "/home.xhtml?faces-redirect=true";
    }

    // ...

}

我当前的会话作用域bean会发生什么?因为甚至连bean本身都存储在HttpSession中?

它仍然可以在当前响应中访问,但在下一个请求中将不再存在。因此,在无效之后触发重定向(一个新请求)是很重要的,否则您仍然会显示来自旧会话的数据。重定向可以通过将faces-redirect=true添加到结果来完成,就像我在上面的示例中所做的那样。另一种发送重定向的方法是使用ExternalContext#redirect()

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

然而,在这种情况下,它的使用是有问题的,因为使用导航结果更简单。

票数 125
EN

Stack Overflow用户

发布于 2012-07-19 17:57:04

public void logout() {
    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
}
票数 13
EN

Stack Overflow用户

发布于 2020-12-11 19:21:29

前端代码为:

<h:form>
<h:commandLink action="#{userManager.logout()}">
       <span>Close your session</span>
</h:commandLink>
</h:form>

后端代码为:

public String logout() {
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
    if (session != null) {
        session.invalidate();
    }
    return "/login.xhtml?faces-redirect=true";  
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5619827

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档