如何在jetty 9中禁用基于JSESSIONID cookie的(以及任何其他)会话跟踪功能



我想为我的无状态或手动维护的状态Spring MVC应用程序禁用Jetty 9中的所有类型的会话跟踪功能,但我找不到任何说明如何做到这一点的工作示例。

我尝试了以下/WEB-INF/spring-config.xml标签:

...
<security:http use-expressions="true"
               disable-url-rewriting="true"
               create-session="stateless">
...

除了以下战争中的/WEB-INF/jetty-web.xml描述符:

<?xml version="1.0"  encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
    <Get name="sessionHandler">
        <Get name="sessionManager">
            <Set name="usingCookies" type="boolean">false</Set>
        </Get>
    </Get>
</Configure>

但每当我试图打开应用程序的任何页面时,我仍然会收到JSESSIONID cookie。有什么提示吗?为什么以及如何修复?

使用servlet 3,可以将会话跟踪模式设置为servlet注册的一部分-ServletContext#setSessionTrackingModes。。。你可以试试。

然而,在你的情况下,我会调查谁在呼叫HttpServletRequest#getSession(...)。在这个方法中放置断点,看看是谁在调用它。应用程序中的某段代码正在初始化会话。

您可以通过在请求完成后立即使会话无效来实现相同的目标。你可以用ServletRequestListener这样做:

public class SessionKiller implements ServletRequestListener {
    public void requestInitialized(ServletRequestEvent sre) {
        // no-op
    }
    public void requestDestroyed(ServletRequestEvent sre) {
        final HttpServletRequest servletRequest = (HttpServletRequest)sre.getServletRequest();
        final HttpSession session = servletRequest.getSession(false);
        if (session != null) {
            session.invalidate();
        }
    }
}

要使用ServletRequestListener,请在Web应用程序的web.xml:中的web-app元素中添加以下内容

<listener>
  <listener-class>YOUR-PACKAGE-NAME.SessionKiller</listener-class>
</listener>

作为用户100464建议的使创建的会话无效的替代方案,我使用了HttpSessionListener,每当有人试图打开会话时(例如通过调用request.getSession()),它都会抛出异常,并删除出现的事件。

public class PreventSessions implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        throw new UnsupportedOperationException("sessions are not allowed");
    }
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        throw new UnsupportedOperationException("sessions are not allowed");
    }
}

Pavel Horal在他的回答中建议的使用Spring Boot的实现简单如下:

import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Collections;
@Configuration
public class WebContainerConfiguration {
  @Bean
  public ServletContextInitializer servletContextInitializer() {
    return servletContext -> servletContext.setSessionTrackingModes(Collections.emptySet());
  }
}

为我做得很好。谢谢!

相关内容

最新更新