我想完全消除 HttpSession - 我可以在 web.xml 中执行此操作吗?我确信有特定于容器的方法可以做到这一点(当我进行 Google 搜索时,这会挤满搜索结果)。
附:这是一个坏主意吗?在我真正需要它们之前,我更喜欢完全禁用它们。
最佳答案
I would like to eliminate the HttpSession completely
您不能完全禁用它。您需要做的只是不通过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 specific documentation .这样, session 将不会保留在未重写 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
),那么您需要创建一个监听 url-pattern
的过滤器的 /*
替换 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);
}
P.S. Is this a bad idea? I prefer to completely disable things until I actually need them.
如果您不需要它们,请不要使用它们。就这样。真的:)
关于java - 我可以关闭 web.xml 中的 HttpSession 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2255814/