1

I have JSF web page using PrimeFaces 5.1 and I want to redirect redirect to some xhtml page once session is expired.

I have set session timeout to 1 minute (for testing it will be set to 30 after that) in web.xml

<session-config>
    <session-timeout>1</session-timeout>
</session-config>

And i have added

<meta http-equiv="refresh" content="#{session.maxInactiveInterval};url=#{request.contextPath}/season_expired.xhtml"/>

to <h:head> of the default template which is used on every page of the application.

Everything works fine for the most of the time (when I move between pages etc..) except when I'm using using some form where every refresh is made by AJAX. Then i get redirected after one minute.

Is there a way to "refresh" session with AJAX?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Kiki
  • 2,243
  • 5
  • 30
  • 43

1 Answers1

2

You can use JS setTimeout() for that which you can clear out with clearTimeout() when an ajax request is made. You can use jsf.ajax.addOnEvent() to register a global ajax event listener function.

<script>
    var redirectToExpired = function() { window.location='#{request.contextPath}/expired.xhtml' };
    var expireTimeMillis = 5000;
    
    window.redirectOnExpire = setTimeout(redirectToExpired, expireTimeMillis);
    jsf.ajax.addOnEvent(function(data) {
        if (data.status == 'begin') {
            clearTimeout(window.redirectOnExpire);
            window.redirectOnExpire = setTimeout(redirectToExpired, expireTimeMillis);
        }
    });
</script>

Like as with the meta refresh header, this is a bit naive as it doesn't work nicely when you have the same webapp open in multiple browser tabs. In a "forgotten" tab, the redirect will still happen in the background while you're active on the same webapp in another tab.

Better is to just not do that all, but rely on ViewExpiredException during a real user action. You can find in javax.faces.application.ViewExpiredException: View could not be restored how to register an error page for that and also how the meta refresh header could be used there.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555