我要啦免费统计

Redirect After Session Timeout in Spring

Overview

Session management is a crucial part for web applications requires user login. If session is not managed properly, the security of data is directly impacted.

Define session timeout in web.xml

In your Spring configuration file, add the following property:

web.xml
1
2
3
<session-config>
<session-timeout>60</session-timeout>
</session-config>

Change the value in the session-timeout tag to the number of timeout minutes you want to set.

Spring Security session timeout settings

Once the session is timeout and if someone tries to access, then we need to redirect our application on any URL. Add the following to the xml configuration file of Spring Security.

spring-security.xml
1
2
3
4
<http>
<session-management invalid-session-url="/login"/>
<logout delete-cookies="JSESSIONID"/>
</http>

The invalid-session-url redirects the user to the login URL when the session is invalid. The delete-cookies is also needed because without it, if someone logs out and tries to login again, the session will still be considered invalid because cookies are still present in the browser.

However, the above session management provided by Spring Security is not sufficient for applications using Ajax calls. Imagine, if you want to create a web application that contains one web page with multiple Javascript and Dojo modules trying to load data from the server back-end using REST calls. After the session becomes invalid, the Ajax calls from Javascript and Dojo will receive 403 Unauthorized Access or other error messages instead of the actual data. This will cause, for example Dojo Enhance Datagrid, to display “Error” message if the user is still on the page, instead of automatically redirect user to the login page. The above timeout mechanism will only be triggered when the user tries to access a new page or refresh the current page after session timeout.

How can we solve this problem? The answer is to add a way to automatically refresh the web page after the session timeout.

Refresh the web page automatically after session timeout

Add the following tag in the section of the web page.

dashboard.jsp
1
<meta http-equiv="refresh" content="<%=session.getMaxInactiveInterval()%>;url=login"/>

In the above code, session.getMaxInactiveInterval() will return the session timeout setting in seconds from web.xml. In our case, the return value will be 3600, corresponding to the 60 minutes we set in web.xml.

In this way, after 60 minutes, the session becomes invalid, and the dashboard.jsp automatically redirects the user to the login page.

If you have any questions, feel free to leave a comment below.