且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

以编程方式更改会话超时

更新时间:2023-09-18 19:57:16

您可以通过

You can change the session timeout by HttpSession#setMaxInactiveInterval() wherein you can specify the desired timeout in seconds.

当您要满足广泛的要求时,例如文件夹/admin中的所有页面或其他内容,那么执行此操作的***位置是创建 Filter 映射到FacesServlet上,它大致完成以下工作:

When you want to cover a broad range of requests for this, e.g. all pages in folder /admin or something, then the best place to do this is to create a Filter which is mapped on the FacesServlet which does roughly the following job:

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpSession session = request.getSession();

    if (request.getRequestURI().startsWith("/admin/")) {
        session.setMaxInactiveInterval(60 * 5); // 5 minutes.
    } else {
        session.setMaxInactiveInterval(60 * 240); // 240 minutes.
    }

    chain.doFilter(req, res);
}

在JSF托管Bean中,ExternalContext#getSession()可以使用该会话:

In a JSF managed bean the session is available by ExternalContext#getSession():

HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession();
// ...

或者,如果您已经在使用JSF 2.1,则还可以使用新的

Or when you're already on JSF 2.1, then you can also use the new ExternalContext#setSessionMaxInactiveInterval() which delegates to exactly that method.