Jetty 11部署Servlet时如何启用JSESSIONID cookie实现会话跟踪
首先确认你的业务代码中触发了会话创建逻辑:只有调用request.getSession() 或 request.getSession(true) 时,容器才会生成新会话并下发JSESSIONID cookie;如果仅调用request.getSession(false)且当前无有效会话,不会触发cookie下发。
以下是两种部署场景下的内置配置方案,均不需要在Servlet中手动编写Cookie操作逻辑:
1. 标准WAR包部署(使用web.xml配置)
属于Servlet规范原生支持的配置,无需修改Jetty服务端参数,直接在你的应用WEB-INF/web.xml中添加会话配置即可强制启用Cookie会话跟踪:
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd" version="5.0"> <!-- 新增会话配置 --> <session-config> <!-- 仅启用Cookie作为会话跟踪方式 --> <tracking-mode>COOKIE</tracking-mode> <!-- 可选:配置会话超时时间,单位分钟 --> <session-timeout>30</session-timeout> <!-- 可选:配置JSESSIONID cookie属性 --> <cookie-config> <name>JSESSIONID</name> <http-only>true</http-only> <!-- HTTPS站点请将secure设为true --> <secure>false</secure> <path>/你的应用上下文路径</path> </cookie-config> </session-config> <!-- 你的其他Servlet配置 --> </web-app>
2. 嵌入式Jetty部署(代码配置)
如果是用嵌入式Jetty启动服务,直接在Servlet上下文配置中指定会话跟踪模式即可:
import jakarta.servlet.SessionTrackingMode; import org.eclipse.jetty.server.session.SessionHandler; import org.eclipse.jetty.servlet.ServletContextHandler; import java.util.EnumSet; // 初始化上下文时添加配置 ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setSessionHandler(new SessionHandler()); // 强制仅使用Cookie会话跟踪 context.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE)); // 后续添加你的Servlet映射、启动Jetty即可
全局Jetty配置排查
如果上述配置后仍未正常下发Cookie,检查Jetty服务的全局配置文件jetty-web.xml中是否存在禁用会话Cookie的配置,将usingCookies属性设为true即可:
<Configure class="org.eclipse.jetty.webapp.WebAppContext"> <Set name="sessionHandler"> <New class="org.eclipse.jetty.server.session.SessionHandler"> <Set name="usingCookies">true</Set> </New> </Set> </Configure>
内容的提问来源于stack exchange,提问作者xiaobin
相关产品推荐
相关产品推荐

