最近有兴趣看了tomcat 8源码对session cookie的处理,才发现web.xml支持对session cookie配置maxage,如果不配置默认就是-1,-1表示这个cookie在当前浏览器窗口有效,存放在内存中而不是硬盘,关掉当前浏览器窗口的话,这个cookie失效,会话结束;如果设置了maxage(不等于-1),则存放到硬盘。
部分源码:
org/apache/catalina/connector/Request.java
createSessionCookie:创建一个sessionCookie,并添加到response
protected Session doGetSession(boolean create) { ................. ................. ................. // Creating a new session cookie based on that session if (session != null && context.getServletContext() .getEffectiveSessionTrackingModes() .contains(SessionTrackingMode.COOKIE)) { Cookie cookie = ApplicationSessionCookieConfig.createSessionCookie( context, session.getIdInternal(), isSecure()); response.addSessionCookieInternal(cookie); } ................. ................. ................. }
org/apache/catalina/core/ApplicationSessionCookieConfig.java
private int maxAge = -1; //默认等于-1
scc.getMaxAge():从scc里取得maxAge
package org.apache.catalina.core; import javax.servlet.SessionCookieConfig; import javax.servlet.http.Cookie; import org.apache.catalina.Context; import org.apache.catalina.LifecycleState; import org.apache.catalina.util.SessionConfig; import org.apache.tomcat.util.res.StringManager; public class ApplicationSessionCookieConfig implements SessionCookieConfig { /** * The string manager for this package. */ private static final StringManager sm = StringManager .getManager(Constants.Package); private boolean httpOnly; private boolean secure; private int maxAge = -1; private String comment; private String domain; private String name; private String path; private StandardContext context; ................. ................. ................. @Override public int getMaxAge() { return maxAge; } ................. ................. ................. /** * Creates a new session cookie for the given session ID * * @param context The Context for the web application * @param sessionId The ID of the session for which the cookie will be * created * @param secure Should session cookie be configured as secure * @return the cookie for the session */ public static Cookie createSessionCookie(Context context, String sessionId, boolean secure) { SessionCookieConfig scc = context.getServletContext().getSessionCookieConfig(); // NOTE: The priority order for session cookie configuration is: // 1. Context level configuration // 2. Values from SessionCookieConfig // 3. Defaults Cookie cookie = new Cookie( SessionConfig.getSessionCookieName(context), sessionId); // Just apply the defaults. cookie.setMaxAge(scc.getMaxAge()); cookie.setComment(scc.getComment()); ................. ................. ................. } }
org/apache/catalina/startup/ContextConfig.java
scc.setMaxAge:读取web.xml里面session-config的max-age并set到scc
package org.apache.catalina.startup; ................. ................. ................. /** * Startup event listener for a <b>Context</b> that configures the properties * of that Context, and the associated defined servlets. * * @author Craig R. McClanahan */ public class ContextConfig implements LifecycleListener { ................. ................. ................. /** * Process a "contextConfig" event for this Context. */ protected synchronized void configureStart() { // Called from StandardContext.start() if (log.isDebugEnabled()) { log.debug(sm.getString("contextConfig.start")); } if (log.isDebugEnabled()) { log.debug(sm.getString("contextConfig.xmlSettings", context.getName(), Boolean.valueOf(context.getXmlValidation()), Boolean.valueOf(context.getXmlNamespaceAware()))); } webConfig(); ................. ................. ................. } ................. ................. ................. /** * Scan the web.xml files that apply to the web application and merge them * using the rules defined in the spec. For the global web.xml files, * where there is duplicate configuration, the most specific level wins. ie * an application's web.xml takes precedence over the host level or global * web.xml file. */ protected void webConfig() { /* * Anything and everything can override the global and host defaults. * This is implemented in two parts * - Handle as a web fragment that gets added after everything else so * everything else takes priority * - Mark Servlets as overridable so SCI configuration can replace * configuration from the defaults */ /* * The rules for annotation scanning are not as clear-cut as one might * think. Tomcat implements the following process: * - As per SRV.1.6.2, Tomcat will scan for annotations regardless of * which Servlet spec version is declared in web.xml. The EG has * confirmed this is the expected behaviour. * - As per http://java.net/jira/browse/SERVLET_SPEC-36, if the main * web.xml is marked as metadata-complete, JARs are still processed * for SCIs. * - If metadata-complete=true and an absolute ordering is specified, * JARs excluded from the ordering are also excluded from the SCI * processing. * - If an SCI has a @HandlesType annotation then all classes (except * those in JARs excluded from an absolute ordering) need to be * scanned to check if they match. */ WebXmlParser webXmlParser = new WebXmlParser(context.getXmlNamespaceAware(), context.getXmlValidation(), context.getXmlBlockExternal()); Set<WebXml> defaults = new HashSet<>(); defaults.add(getDefaultWebXmlFragment(webXmlParser)); WebXml webXml = createWebXml(); // Parse context level web.xml InputSource contextWebXml = getContextWebXmlSource(); if (!webXmlParser.parseWebXml(contextWebXml, webXml, false)) { ok = false; } ................. ................. ................. configureContext(webXml); ................. ................. ................. } private void configureContext(WebXml webxml) { ................. ................. ................. SessionConfig sessionConfig = webxml.getSessionConfig(); if (sessionConfig != null) { if (sessionConfig.getSessionTimeout() != null) { context.setSessionTimeout( sessionConfig.getSessionTimeout().intValue()); } SessionCookieConfig scc = context.getServletContext().getSessionCookieConfig(); scc.setName(sessionConfig.getCookieName()); scc.setDomain(sessionConfig.getCookieDomain()); scc.setPath(sessionConfig.getCookiePath()); scc.setComment(sessionConfig.getCookieComment()); if (sessionConfig.getCookieHttpOnly() != null) { scc.setHttpOnly(sessionConfig.getCookieHttpOnly().booleanValue()); } if (sessionConfig.getCookieSecure() != null) { scc.setSecure(sessionConfig.getCookieSecure().booleanValue()); } if (sessionConfig.getCookieMaxAge() != null) { scc.setMaxAge(sessionConfig.getCookieMaxAge().intValue()); } if (sessionConfig.getSessionTrackingModes().size() > 0) { context.getServletContext().setSessionTrackingModes( sessionConfig.getSessionTrackingModes()); } } ................. ................. ................. } ................. ................. ................. }
org/apache/tomcat/util/descriptor/web/WebRuleSet.java
/session-config/cookie-config/max-age为web.xml的配置项
/** * <p>Add the set of Rule instances defined in this RuleSet to the * specified <code>Digester</code> instance, associating them with * our namespace URI (if any). This method should only be called * by a Digester instance.</p> * * @param digester Digester instance to which the new Rule instances * should be added. */ @Override public void addRuleInstances(Digester digester) { ................. ................. ................. digester.addRule(fullPrefix + "/session-config", sessionConfig); digester.addObjectCreate(fullPrefix + "/session-config", "org.apache.tomcat.util.descriptor.web.SessionConfig"); digester.addSetNext(fullPrefix + "/session-config", "setSessionConfig", "org.apache.tomcat.util.descriptor.web.SessionConfig"); digester.addCallMethod(fullPrefix + "/session-config/session-timeout", "setSessionTimeout", 0); digester.addCallMethod(fullPrefix + "/session-config/cookie-config/name", "setCookieName", 0); digester.addCallMethod(fullPrefix + "/session-config/cookie-config/domain", "setCookieDomain", 0); digester.addCallMethod(fullPrefix + "/session-config/cookie-config/path", "setCookiePath", 0); digester.addCallMethod(fullPrefix + "/session-config/cookie-config/comment", "setCookieComment", 0); digester.addCallMethod(fullPrefix + "/session-config/cookie-config/http-only", "setCookieHttpOnly", 0); digester.addCallMethod(fullPrefix + "/session-config/cookie-config/secure", "setCookieSecure", 0); digester.addCallMethod(fullPrefix + "/session-config/cookie-config/max-age", "setCookieMaxAge", 0); digester.addCallMethod(fullPrefix + "/session-config/tracking-mode", "addSessionTrackingMode", 0); ................. ................. ................. }
从上面的addRuleInstances里看出session cookie maxage的配置在工程里的web.xml的session-config里,比如:
<session-config> # 设置Session数据30分钟后过期-服务端 <session-timeout>30</session-timeout> <cookie-config> # 设置SessionId在Cookie中的名称 <name>sop_session_id</name> # 设置SessionId存在哪个路径下,跟路径则可全站使用 <path>/</path> # 设置是否只读 <http-only>true</http-only> # 设置SessionId30分钟后过期 <max-age>1800</max-age> # 设置安全机制,只有https才能获取 <secure>true</secure> </cookie-config> </session-config>
疑问:如果session-timeout和max-age我都设置1年,那不是一年都不用登录了?
相关推荐
标题中的“tomcat8+memcached session共享”指的是在Tomcat 8服务器中利用Memcached进行session共享的技术实践。在分布式系统中,session共享是一个重要的问题,因为用户在访问不同的服务器节点时,需要保持登录状态...
标题中的“Tomcat8亲测可用 tomcat-redis-session-manager的jar包”指的是一个专为Tomcat8设计的,用于管理session的扩展组件。这个组件实现了将Tomcat应用服务器中的用户session数据存储到Redis分布式缓存系统中,...
《深入理解Tomcat-Redis-Session-Manager:在Tomcat7和Tomcat8中的应用》 在现代Web应用程序开发中,session管理是一个至关重要的环节,它涉及到用户会话的持久化和跨请求的数据共享。传统的session管理方式在高...
【描述】中提到的"所需的tomcat-redis-session-manager所有的jar包下载"意味着我们需要了解如何配置和使用这个第三方库,以便在Tomcat8环境中存储和检索用户的session数据到Redis缓存系统。测试环境使用的是JDK1.8,...
通过研究Tomcat8的源码,我们可以深入理解其内部工作流程,学习如何定制和优化服务器配置,以适应不同的Web应用需求。这不仅有助于提升开发效率,还能帮助我们解决在实际项目中遇到的性能瓶颈和安全问题。因此,对...
它将Tomcat中的Session数据序列化后存储到Redis中,当需要时再从Redis中读取,确保所有服务器都能访问到统一的Session信息。 **三、工作原理** 1. **Session创建与更新**:当用户请求到达服务器时,如果创建或更新...
《深入解析Tomcat-Redis-Session-Manager源码》 在现代Web应用中,服务器端会话管理是一个至关重要的部分,特别是在高并发、分布式环境中。Tomcat作为最流行的Java Servlet容器,提供了丰富的功能来支持这一需求。...
2. **获取源码**:使用Git克隆Tomcat8的源码仓库,或者直接从Apache网站下载源码压缩包。 3. **配置Maven**:如果选择使用Maven,需要在`pom.xml`文件中配置正确的依赖关系。这包括设置JDK版本、Tomcat的版本以及...
总之,实现Tomcat8集群中的Session共享是一个涉及到服务器配置、网络通信和数据存储的复杂过程。正确配置和选择合适的共享策略是确保Web应用在高并发环境下仍能提供良好用户体验的关键。在使用提供的"session共享包...
基于之前支持Tomcat7以下的redis-Session共享机制 进行相关适配的修改打包,里面包含所需Jar包以及相关的说明配置文档,包括:--单点授权Reids配置;...适用于Tomcat8的容器环境,8以上的环境暂未测试,不过应该也兼容
tomcat8 redis session共享,提供commons-pool2-2.3.jar,jedis-2.7.2.jar和修改后的tomcat-redis-session-manager-master-2.0.0.jar及部署文档
tomcat8 Redis集群 同步Session 中用到的jar 附带tomcat content.xml配置文件
2. Tomcat 8与JDK 1.7、1.8:Tomcat 8是广泛使用的版本,JDK 1.7和1.8则兼顾了对老版本Java的支持和新特性的利用。 3. Tomcat 8.5与JDK 1.7:优化了性能和功能,对JDK 1.7的支持意味着能运行在更多环境中。 4. ...
tomcat-redis-session-manager-1.2-tomcat-7-java-7tomcat-redis-session-manager-1.2-tomcat-7-java-7tomcat-redis-session-manager-1.2-tomcat-7-java-7tomcat-redis-session-manager-1.2-tomcat-7-java-7tomcat-...
标题 "tomcat8-redis-session共享" 涉及到的是在Tomcat 8中使用Redis作为Session共享存储的解决方案。这是一个常见的需求,特别是在分布式系统中,为了保持用户会话的一致性,需要将Session数据在多台服务器之间共享...
- 配置Nginx,启用负载均衡模块,并设置Session亲和规则,例如基于cookie的`hash`策略。 - 对Redis进行必要的安全和性能调优,如设置合适的过期时间、限制连接数等。 7. **优点**:使用Redis同步Session可以避免...
3. "tomcat-cluster-redis-session-manager-3.0.jar":这是Tomcat Redis Session Manager的核心组件,实现了Tomcat的Session监听器和Manager接口,使得Tomcat能够将Session数据存储到Redis中,并在需要时从Redis中...
从Tomcat 6.x 开始,配置JSessionID在Cookie中的名称变得更加灵活。可以通过在`server.xml` 文件中的 `<Context>` 标签内设置 `sessionCookieName` 属性来完成这一操作。 **示例配置:** ```xml ... ``` 其中 ...
本压缩包包含的是Tomcat8的源码,适合开发者进行深入学习和研究,了解其内部工作原理。通过在Eclipse集成开发环境中直接运行源码,可以方便地调试和分析Tomcat的执行流程。 首先,我们需要了解Tomcat的基本架构。...