Java Session Timeout – Java会话超时

最后修改: 2013年 7月 26日


1. Overview


This tutorial will show how to set up session timeout in a Servlet based web application.


2. Global Session Timeout in the web.xml


The timeout of all Http Sessions can be configured in the web.xml of the web application:


<?xml version="1.0" encoding="UTF-8"?>
<web-app ...>



Note that the value of the timeout is set in minutes, not in seconds.


An interesting sidenode is that, in a Servlet 3.0 environment where annotations may be used instead of the XML deployment descriptor, there is no way to programmatically set the global session timeout. Programmatic configuration for session timeout does have an open issue on the Servlet Spec JIRA – but the issue has not yet been scheduled.

一个有趣的分支是,在Servlet 3.0环境中,可以使用注解而不是XML部署描述符,但没有办法以编程方式设置全局会话超时。会话超时的程序化配置在Servlet Spec JIRA上确实有一个开放的问题–但该问题还没有被安排。

3. Programmatic Timeout per Individual Session


The timeout of the current session only can be specified programmatically via the API of the javax.servlet.http.HttpSession:


HttpSession session = request.getSession();

As opposed to the <session-timeout> element which had a value in minutes, the setMaxInactiveInterval method accepts a value in seconds.


4. Tomcat Session Timeout


All Tomcat servers provide a default web.xml file that can be configured globally for the entire web server – this is located in:

所有Tomcat服务器都提供一个默认的web.xml文件,可以为整个Web服务器进行全局配置 – 这位于。


This default deployment descriptor does configure a <session-timeout> with to a value of 30 minutes.


Individual deployed applications, providing their own timeout values in their own web.xml descriptors will have priority over and will override this global web.xml configuration.


Note that the same is possible in Jetty as well: the file is located in:



5. Conclusion


This tutorial discussed the practical aspects of how to configure the timeout of the HTTP Session in a Servlet Java application. We also illustrated how this can be set at the web server level, both in Tomcat as well as in Jetty.

本教程讨论了如何在Servlet Java应用程序中配置HTTP会话的超时的实际问题。我们还说明了如何在Tomcat和Jetty的Web服务器层面上进行设置。

The implementation of these examples can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is.

这些示例的实现可以在github 项目中找到 – 这是一个基于 Eclipse 的项目,因此应该很容易导入并按原样运行。

When the project runs locally, the homepage html can be accessed at: