我可以关闭 web.xml 中的 HttpSession 吗?

新手上路,请多包涵

我想完全消除 HttpSession - 我可以在 web.xml 中这样做吗?我确信有特定于容器的方法可以做到这一点(当我进行谷歌搜索时,这就是搜索结果中拥挤的原因)。

PS 这是个坏主意吗?我更喜欢完全禁用某些东西,直到我真正需要它们为止。

原文由 les2 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 476
2 个回答

我想完全消除 HttpSession

你不能完全禁用它。您需要做的就是 不要 通过 request.getSession()request.getSession(true) 在您的 web 应用程序代码中的任何位置获取它的句柄,并确保您的 JSP 不会隐式地执行此操作设置 <%@page session="false"%>

如果您主要关心的是禁用在 HttpSession 幕后使用的 cookie,那么您可以在 Java EE 5 / Servlet 2.5 中仅在服务器特定的 webapp 配置中这样做。例如,在 Tomcat 中,您可以在 — 元素中将 cookies 属性设置为 false <Context> 元素。

 <Context cookies="false">

另请参阅此 Tomcat 特定文档。这样,会话将不会保留在未重写 URL 的后续请求中——仅当您出于某种原因从请求中获取它时。毕竟,如果你不需要它, 不要抓住它,那么它就根本不会被创建/保留。

或者,如果您已经在使用 Java EE 6 / Servlet 3.0 或更新版本,并且真的想通过 web.xml 来实现,那么您可以使用 --- 中的新 <cookie-config> web.xml 如下将最大年龄归零:

 <session-config>
    <session-timeout>1</session-timeout>
    <cookie-config>
        <max-age>0</max-age>
    </cookie-config>
</session-config>

如果您想在您的网络应用程序中进行硬编码,以便 getSession() 永远不会返回 HttpSession (或“空” HttpSession ),那么您需要创建filter listening on an url-pattern of /* which replaces the HttpServletRequest with a HttpServletRequestWrapper implementation which returns on all getSession() 方法 null ,或虚拟自定义 HttpSession 什么都不做,甚至抛出 UnsupportedOperationException 的实现。

 @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    chain.doFilter(new HttpServletRequestWrapper((HttpServletRequest) request) {
        @Override
        public HttpSession getSession() {
            return null;
        }
        @Override
        public HttpSession getSession(boolean create) {
            return null;
        }
    }, response);
}


PS 这是个坏主意吗?我更喜欢完全禁用某些东西,直到我真正需要它们为止。

如果您不需要它们,就不要使用它们。就这样。真的 :)

原文由 BalusC 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您正在构建一个无状态的高负载应用程序,您可以像这样禁用使用 cookie 进行会话跟踪(非侵入性,可能与容器无关):

 <session-config>
    <tracking-mode>URL</tracking-mode>
</session-config>

要执行此架构决策,请编写如下内容:

 public class PreventSessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
    throw new IllegalStateException("Session use is forbidden");
}

@Override
public void sessionDestroyed(HttpSessionEvent se) {
    throw new IllegalStateException("Session use is forbidden");
}
}

并将其添加到 web.xml 并修复它因该异常而失败的地方:

 <listener>
    <listener-class>com.ideas.bucketlist.web.PreventSessionListener</listener-class>
</listener>

原文由 Dmytro Voloshyn 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题