tags:

views:

636

answers:

1

I have a JSF app and would like to have the user auto logout after a period of inactivity. Is there an standard way to do this?

+1  A: 

Generally, the server (Tomcat, Glassfish...) that hosts the web application handles a timeout for a session.

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:

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

This will set the timeout to 30 minutes.

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.

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() { 
    } 

}
romaintaz