我需要将Tomcat中应用程序会话的最大持续时间配置为24小时。
我在文档中找不到合适的配置:
https://tomcat.apache.org/tomcat-8.5-doc/config/http.html
(有sessionTimeout,SSLHostConfig但是我需要Connector配置;我们在Tomcat之前终止WebServer中的SSL连接,但是由Tomcat处理会话管理。)
sessionTimeout
SSLHostConfig
Connector
添加
我们已经处理了会话过期超时Tomcat Session Timeoutweb.xml。
最大持续时间超时意味着即使用户在所有时间内都处于活动状态,其应用程序会话在最大持续时间超时后也会失效。
HttpSessionListener 只会通知会话的创建和销毁,而不会在每个页面请求上被调用。
HttpSessionListener
我将实现一个过滤器来检查会话创建时间,并使会话无效,并设置标头或重定向。
在web.xml中添加:
<filter> <filter-name>Max Session Duration</filter-name> <filter-class>com.your.package.MaxSessionDurationFilter</filter-class> <init-param> <!-- Maximum session duration in hours --> <param-name>maxduration</param-name> <param-value>24</param-value> </init-param> </filter>
和类似的映射
<filter-mapping> <filter-name>Max Session Duration</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping>
然后过滤器的实现就像:
package com.your.package; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MaxSessionDurationFilter implements Filter { private final long oneHourMillis = 1000*60*60; private long maxDuration; private FilterConfig filterConfig; @Override public void init(FilterConfig fc) throws ServletException { filterConfig = fc; maxDuration = Long.parseLong(filterConfig.getInitParameter("maxduration")); } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) req; HttpServletResponse httpResp = (HttpServletResponse) resp; final long creationTime = httpReq.getSession().getCreationTime(); final long currentTime = System.currentTimeMillis(); if (currentTime-creationTime > maxDuration*oneHourMillis) { httpReq.getSession().invalidate(); // Could also set headers to 403 forbidden // httpResp.setStatus(HttpServletResponse.SC_FORBIDDEN); httpResp.sendRedirect("expiredsession.jsp"); } else { chain.doFilter(req, resp); } } @Override public void destroy() { } }