les*_*es2 55 java session web.xml web-applications
我想完全消除HttpSession - 我可以在web.xml中这样做吗?我确信有容器特定的方法可以做到这一点(当我进行谷歌搜索时,搜索结果会出现这种情况).
PS这是个坏主意吗?在我真正需要它之前,我更喜欢完全禁用它们.
Bal*_*usC 73
我想完全消除HttpSession
你不能完全禁用它.您需要做的就是不要通过Web应用程序代码中的任何一个request.getSession()或request.getSession(true)任何地方来处理它,并确保您的JSP不会通过设置隐式地执行此操作<%@page session="false"%>.
如果您的主要关注点实际上是禁用了幕后使用的cookie HttpSession,那么您可以在Java EE 5/Servlet 2.5中仅在特定于服务器的Web应用程序配置中执行此操作.在例如Tomcat的,你可以在设置cookies属性false的<Context>元素.
<Context cookies="false">
Run Code Online (Sandbox Code Playgroud)
另请参阅此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>
Run Code Online (Sandbox Code Playgroud)
如果你想在你的web应用进行硬编码,这样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);
}
Run Code Online (Sandbox Code Playgroud)
PS这是个坏主意吗?在我真正需要它之前,我更喜欢完全禁用它们.
如果您不需要它们,请不要使用它们.就这样.真的:)
小智 8
如果您正在构建无状态高负载应用程序,则可以禁用使用cookie进行会话跟踪(非侵入式,可能与容器无关):
<session-config>
<tracking-mode>URL</tracking-mode>
</session-config>
Run Code Online (Sandbox Code Playgroud)
要执行此体系结构决策,请执行以下操作:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
并将其添加到web.xml并使用该异常修复失败的位置:
<listener>
<listener-class>com.ideas.bucketlist.web.PreventSessionListener</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)
在带有 Java Config 的 Spring Security 3 中,您可以使用 HttpSecurity.sessionManagement():
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
Run Code Online (Sandbox Code Playgroud)
xml看起来像这样;
<http create-session="stateless">
<!-- config -->
</http>
Run Code Online (Sandbox Code Playgroud)
顺便说一下,NEVER 和 STATELESS 的区别
NEVER:Spring Security 永远不会创建 HttpSession,但会使用 HttpSession 如果它已经存在
无状态:Spring Security 永远不会创建 HttpSession 并且永远不会使用它来获取 SecurityContext
| 归档时间: |
|
| 查看次数: |
47311 次 |
| 最近记录: |