27

I am using JSF RI 1.1. How to redirect to index page if session time out happens?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Paul
  • 1,380
  • 3
  • 12
  • 21

3 Answers3

48

There are two ways which can be combinied:

  1. Make use of the <meta> refresh header in the HTML <head> element in combination with HttpSession#getMaxInactiveInterval() which returns the remnant of seconds the session has yet to live.

    <meta http-equiv="refresh" content="${pageContext.session.maxInactiveInterval};url=index.jsf">
    

    This approach will automatically redirect the page to the given url when the session expires.

  2. Catch ViewExpiredException in web.xml:

    <error-page>
        <exception-type>javax.faces.application.ViewExpiredException</exception-type>
        <location>/index.jsf</location>
    </error-page>
    

    This approach will automatically forward the request to the given <location> when a POST request has been fired (h:commandButton, h:commandLink, etc) while the session is expired.

Note that I personally would prefer an intermediate "Session Expired" warning page or alert to avoid "wtf?" experiences and thus improve the user experience. Even more, I would as well prefer firing an ajaxical poll every minute when the client has shown activity by listening on click and keypress, so that the session's lifetime can be postponed more.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • I'm using the built-in myfaces mechanism for this, but the error-page is quite a very good way to do it. – Bozho Mar 30 '10 at 12:14
  • Hi BalusC, Is ajaxical possible and can we use Ajax in jsf 1.1. If yes,How to make the ajaxical to postponed session lifetime. – Paul Mar 30 '10 at 13:47
  • Just use JavaScript/jQuery and a simple servlet in the same context/session which does a `request.getSession()`. I posted an example here before: http://stackoverflow.com/questions/2319020/mvc-with-jquery-handling-session-expire/2319211#2319211 – BalusC Mar 30 '10 at 13:50
  • 1
    If using the latest facelets. Use #{session.maxInactiveInterval} instead. – Mark W Apr 29 '15 at 08:37
10

JSF2:

<meta http-equiv="refresh" content="#{facesContext.externalContext.sessionMaxInactiveInterval};url=#{request.contextPath}/index.xhtml"/>
Cerbenus
  • 213
  • 3
  • 11
6

You can use a Filter to catch the particular exception indicating the timeout, and redirect from there.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 1
    @Paul if you try it and it works, make sure you mark the answer as accepted (same goes for your other questions). Marking is accepted is achieved by the tick below the vote counter. – Bozho Mar 30 '10 at 11:33
  • Can you post the solution? It absolutely does not work why what I tried. – Kawu Mar 12 '20 at 23:13