我尝试了不同的方法来设置自定义的 cookie 名称。但是没有一个在我的配置中工作。
我有一个在独立 Tomcat 中运行的 Spring Boot 应用程序。
我试图在派生自 SpringBootServletInitializer
的 SpringBootApplication
类中设置 cookie 名称:
@Value("${session.cookie.name}")
private String sessionCookieName;
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.getSessionCookieConfig().setName(sessionCookieName);
super.onStartup(servletContext);
}
我还尝试将 bean 定义为 DefaultCookieSerializer
:
@Value("${session.cookie.name}")
private String sessionCookieName;
@Bean
public DefaultCookieSerializer defaultCookieSerializer(){
DefaultCookieSerializer defaultCookieSerializer = new DefaultCookieSerializer();
defaultCookieSerializer.setCookieName(sessionCookieName);
return defaultCookieSerializer;
}
但到目前为止没有任何效果,我总是得到默认的 JSESSONID
而不是我配置的 session.cookie.name
还有其他方法可以自定义cookie名称吗?
最佳答案
我按照建议尝试了 TomcatContextCustomizer。但我认为当您将应用程序部署为 WAR 文件时它不起作用,因为它仅适用于嵌入式 tomcat。
我通过添加 web.xml 解决了这个问题。在文件夹 src/main/webapp/WEB-INF 中。我对这个解决方案不是很满意,因为我不想在我的 spring boot 应用程序中使用 web.xml。但它有效...
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
metadata-complete="true">
<session-config>
<session-timeout>30</session-timeout>
<cookie-config>
<name>CUSTOM_SESSION_ID</name>
<http-only>true</http-only>
</cookie-config>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
</web-app>
如果有更好的解决方案请告诉我
关于spring - 如何在独立 Tomcat 中运行的 Spring Boot 应用程序中设置 cookie 名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44657449/