1. Overview
1.概述
This tutorial will show how to set up session timeout in a Servlet based web application.
本教程将展示如何在基于Servlet的Web应用程序中设置会话超时。
2. Global Session Timeout in the web.xml
2、web.xml中的全局会话超时
The timeout of all Http Sessions can be configured in the web.xml of the web application:
所有Http会话的超时可以在Web应用程序的web.xml中进行配置。
<?xml version="1.0" encoding="UTF-8"?>
<web-app ...>
...
<session-config>
<session-timeout>10</session-timeout>
</session-config>
</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
3.每个会话的程序性超时
The timeout of the current session only can be specified programmatically via the API of the javax.servlet.http.HttpSession:
可以通过javax.servlet.http.HttpSession的API以编程方式指定当前会话的超时。
HttpSession session = request.getSession();
session.setMaxInactiveInterval(10*60);
As opposed to the <session-timeout> element which had a value in minutes, the setMaxInactiveInterval method accepts a value in seconds.
与<session-timeout>元素相比,setMaxInactiveInterval方法接受的是秒的值。
4. Tomcat Session Timeout
4.Tomcat会话超时
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服务器进行全局配置 – 这位于。
$tomcat_home/conf/web.xml
This default deployment descriptor does configure a <session-timeout> with to a value of 30 minutes.
这个默认的部署描述符确实配置了一个<session-timeout>,数值为30分钟。
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.
单个部署的应用程序,在自己的web.xml描述符中提供自己的超时值,将优先于并将覆盖这个全局web.xml配置。
Note that the same is possible in Jetty as well: the file is located in:
请注意,同样是在Jetty中也是可能的:该文件位于。
$jetty_home/etc/webdefault.xml
5. Conclusion
5.结论
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:
当项目在本地运行时,可以通过以下网址访问主页html。