【问题标题】:How to invalidate session in JSF 2.0?如何在 JSF 2.0 中使会话无效?
【发布时间】:2015-10-18 09:07:08
【问题描述】:

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

private void reset() {
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
            .getExternalContext().getSession(false);
    session.invalidate();
}
  1. 这种方法正确吗?有没有办法不碰 ServletAPI?
  2. 考虑一个场景,其中@SessionScoped UserBean 处理 用户的登录-注销。我在同一个bean中有这个方法。现在 当我完成必要的数据库后调用reset() 方法时 更新,我当前的会话范围 bean 会发生什么?自从 甚至 bean 本身都存储在 HttpSession?

【问题讨论】:

    标签: session jsf-2 httpsession managed-bean session-scope


    【解决方案1】:

    首先,这个方法正确吗?有没有不接触 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");
    }
    

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

    【讨论】:

    • @BalusC,ExternalContext#invalidateSession()HttpSession#invalidate()有什么区别?
    • @Patrick:功能上,没什么。他们都做同样的事情。 ExternalContext#invalidateSession() 在幕后调用 HttpSession#invalidate()(另请参阅我的答案中的 javadoc 链接)。从设计技术上讲,ExternalContext 方法更好。您基本上应该努力在您的任何 JSF 相关工件中实现 javax.servlet.* 导入。
    • SSL 会话怎么样?是否可以使其无效?因为我通过建议的方法尝试不成功
    【解决方案2】:
    public void logout() {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    }
    

    【讨论】:

      【解决方案3】:

      前端代码是:

      <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";  
      }
      

      【讨论】:

        猜你喜欢
        • 2012-03-22
        • 1970-01-01
        • 2013-07-22
        • 2012-01-11
        • 2013-08-02
        • 2011-12-05
        • 2016-11-18
        相关资源
        最近更新 更多