首页 文章

如何在JSF 2.0中使会话无效?

提问于
浏览
58

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

private void reset() {
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
            .getExternalContext().getSession(false);
    session.invalidate();
}
  • 这种方法是否正确?有没有办法没有触及ServletAPI?

  • 考虑一种情况,其中 @SessionScoped UserBean处理用户的登录注销 . 我在同一个bean中有这个方法 . 现在当我完成必要的数据库更新后调用 reset() 方法时,我当前的会话作用域bean会发生什么?因为即使bean本身也存储在_1739205中?

2 回答

  • 123

    首先,这种方法是否正确?有没有办法没有触及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";
        }
    
        // ...
    
    }
    

    我当前的会话scoped 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");
    }
    

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

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

相关问题