servlets - web.xml 中的 session-timeout 和 max-age 有什么区别?

标签 servlets cookies web.xml session-timeout

我不确定我是否理解:

<session-config>
    <session-timeout>30</session-timeout> <!-- 30 minutes! -->
    <cookie-config>
        <http-only>true</http-only>
        <max-age>1800</max-age> <!-- 1800 seconds: 30 minutes! -->
    </cookie-config>
    <tracking-mode>COOKIE</tracking-mode>
</session-config>

另外,有没有办法在 web.xml 中配置所有 cookie?这似乎仅适用于 session cookie。我是否需要为此类功能设置过滤器?

最佳答案

为什么我们甚至需要这个?引用 Servlet 3.0 规范:

In the HTTP protocol, there is no explicit termination signal when a client is no longer active. This means that the only mechanism that can be used to indicate when a client is no longer active is a time out period.



web-commons 模式真的很好地解释了它:

The session-timeout element defines the default session timeout interval for all sessions created in this web application. The specified timeout must be expressed in a whole number of minutes.

If the timeout is 0 or less, the container ensures the default behaviour of sessions is never to time out. If this element is not specified, the container must set its default timeout period.



web-commons 模式也为我们提供了一些关于 max-age 的信息。元素:

The lifetime (in seconds) that will be assigned to any session tracking cookies created by this web application. Default is -1



并回答您的最后一个问题:

Also, is there any way to configure ALL cookies in web.xml? This seems to apply to session cookies only. Do I need a filter for such feature?



我不这么认为。
恕我直言,最简单的方法是子类化
HttpServletResponseWrapper 覆盖 addCookie()方法。

所以总结一下:
  • session 超时 配置 session 将在消耗服务器资源周围停留多长时间,即使没有被主动访问。
  • 最大年龄 配置客户端浏览器将保留 session cookie 的时间。此设置仅适用于 cookie 的生命周期:如果您使用 URL 重写,它不会做任何事情,并且它与 session 在服务器端保留的时间完全无关。默认值 -1,只要浏览器 session 处于事件状态,就会保留 cookie。


  • 有用的链接:

    Servlet 3.1 JSR-340 规范页面:
    http://download.oracle.com/otndocs/jcp/servlet-3_1-fr-eval-spec/index.html

    web-commons XSD 可在以下位置获得:
    http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/web-common_3_0.xsd

    关于servlets - web.xml 中的 session-timeout 和 max-age 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35105410/

    相关文章:

    java - 为什么此 XML 会产生 "...must be well-formed"验证错误?

    java - 使 session 无效后我的 session 未变为 Null

    java - 为什么我的 cookie 值没有设置?

    java - 如何一次捕获所有错误代码

    java - Glassfish jdbc/数据库查找失败

    javascript - 为什么即使在设置 "esponse.addHeader("Access-Control-Allow-Origin", "*");"在 servlet 中,CORS 请求也会失败?

    java - Ajax 调用中返回 null json

    java - 如何删除 cookie

    javascript - 注销时删除登录 cookie

    spring - 使用 Spring MVC 时无法让 Tomcat 提供一些静态文件