Help catching session timeout in spring

2019-04-14 15:59发布

问题:

I have a simple Spring 3 MVC application. I am using a sessionAttribute and everything works fine except when I let the page sit for 30 minutes or longer. I then get a

org.springframework.web.HttpSessionRequiredException

telling me my object is not found in session.

I am thinking I need to somehow redirect back to the same page when a session timeout occurs. I am not sure how to do this correctly with spring.

There is no login required and I am already checking if the object is null.

Any suggestions would be appreciated.

Thanks

回答1:

You can add error-page binding to HttpSessionRequiredException which will redirect to first page in your application

example:

web.xml

<web-app>
    <error-page>
        <exception-type>org.springframework.web.HttpSessionRequiredException</exception-type>
        <location>/index.jsp</location>
    </error-page>
</web-app>


回答2:

There is no way you can just redirect "back to the same page". You session is gone, that is the cookie you have on the client is no longer correspond to any session in the servlet container, because session object was deleted from memory. Totally, irreversibly.

You may increase session timeout. This is application configuration, not Spring:

web.xml:

   <session-config>
     <session-timeout>120</session-timeout>
   </session-config>

will give you two hours of idle session.

Note that sessions are not free. They consume resources (memory and disk, when serialized). If the same user can re-login multiple time, they'll have multiple idle sessions, and potentially could cause you DoS.

P.S. If you OK with gone session, and just want to establish another one right away, you can always do it in a filter, Spring or not. Spring may have their own listeners. You'd have to place something into that brand new session to make your request work.