简体   繁体   English

在JSF应用程序中自动注销

[英]Auto-logout in JSF Application

I have a JSF app and would like to have the user auto logout after a period of inactivity. 我有一个JSF应用程序,并希望用户在一段时间不活动后自动注销。 Is there an standard way to do this? 有没有标准的方法来做到这一点?

Generally, the server (Tomcat, Glassfish...) that hosts the web application handles a timeout for a session. 通常,托管Web应用程序的服务器(Tomcat,Glassfish ...)会处理会话超时。

For example, in Tomcat, you can define the session timeout for a particular web application by adding the folowing lines in the web.xml file: 例如,在Tomcat中,您可以通过在web.xml文件中添加以下行来定义特定Web应用程序的会话超时:

<session-config>
    <session-timeout>30</session-timeout>
</session-config>

This will set the timeout to 30 minutes. 这会将超时设置为30分钟。

When a user does not send any request during a time greater that this defined timeout, the session on the server is invalidated. 当用户在超过此定义的超时的时间内未发送任何请求时,服务器上的会话将失效。 If the user tries to reconnect after the session has been invalidated, he will generally be redirected to another page or to an error page. 如果用户在会话失效后尝试重新连接,则通常会将其重定向到另一个页面或错误页面。

You can develop your own JSF Filter that will automatically redirect the user to a timeout.html page. 您可以开发自己的JSF过滤器,它将自动将用户重定向到timeout.html页面。 Here is an example of such a filter : 以下是此类过滤器的示例:

public class TimeoutFilter implements Filter { 

    private static final String TIMEOUT_PAGE = "timeout.html"; 
    private static final String LOGIN_PAGE = "login.faces";  

    public void init(FilterConfig filterConfig) throws ServletException { 
    } 

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { 
    if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) { 
        HttpServletRequest requestHttp = (HttpServletRequest) request; 
        HttpServletResponse responseHttp = (HttpServletResponse) response; 
        if (checkResource(requestHttp)) {
            String requestPath = requestHttp.getRequestURI();
            if (checkSession(requestHttp)) { 
                String timeoutUrl = hRequest.getContextPath() + "/" + TIMEOUT_PAGE; 
                responseHttp.sendRedirect(timeoutUrl); 
                return; 
            } 
        } 
        filterChain.doFilter(request, response);
    } 

    private boolean checkResource(HttpServletRequest request) { 
        String requestPath = request.getRequestURI(); 
        return !(requestPath.contains(TIMEOUT_PAGE) || requestPath.contains(LOGIN_PAGE) || requestPath.equals(hRequest.getContextPath() + "/")); 
    } 

    private boolean checkSession(HttpServletRequest request) { 
        return request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid(); 
    }

    public void destroy() { 
    } 

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM