我想彻底消除 HttpSession
您不能完全禁用它。您需要做的只是不通过request.getSession() 或request.getSession(true) 在您的Web 应用程序代码中的任何位置处理它,并确保您的JSP 不会通过设置隐式执行此操作<%@page session="false"%>.
如果您真正关心的是禁用在 HttpSession 幕后使用的 cookie,那么您可以在 Java EE 5 / Servlet 2.5 中仅在特定于服务器的 webapp 配置中这样做。例如在 Tomcat 中,您可以在 <Context> 元素中将 cookies 属性设置为 false。
<Context cookies="false">
另见Tomcat specific documentation。这样,会话将不会保留在未重写 URL 的后续请求中——仅当您出于某种原因从请求中获取它时。毕竟,如果你不需要它,只是不要抓住它,那么它根本不会被创建/保留。
或者,如果您已经在使用 Java EE 6 / Servlet 3.0 或更新版本,并且真的想通过 web.xml 来实现,那么您可以使用 web.xml 中的新 <cookie-config> 元素,如下所示归零-超出最大年龄:
<session-config>
<session-timeout>1</session-timeout>
<cookie-config>
<max-age>0</max-age>
</cookie-config>
</session-config>
如果您想在您的网络应用程序中进行硬编码,以便 getSession() 永远不会返回 HttpSession(或“空”HttpSession),那么您需要创建一个过滤器来监听 url-pattern 的 @ 987654339@ 将HttpServletRequest 替换为HttpServletRequestWrapper 实现,该实现返回所有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);
}
附注这是一个坏主意吗?在我真正需要它们之前,我更喜欢完全禁用它们。
如果您不需要它们,请不要使用它们。就这样。真的:)