参考代码 :Spring Boot: remove jsessionid from url
我的SpringBoot用2.0.*,答案中的第一二个方案亲测无效。
应该在继承了Configuration里面加入第三种方案所示的代码
@Configuration
//WebMvcConfigurerAdapter在2.0.*中已作废,有WebMvcConfigurer,WebMvcConfigurationSupport两种方案。
//public class WebSecurityConfig extends WebMvcConfigurerAdapter{
public class WebSecurityConfig implements WebMvcConfigurer {
//public class WebSecurityConfig extends WebMvcConfigurationSupport {
@Bean
public ServletContextInitializer servletContextInitializer() {
return new ServletContextInitializer() { @Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.setSessionTrackingModes(Collections.singleton(SessionTrackingMode.COOKIE));
SessionCookieConfig sessionCookieConfig=servletContext.getSessionCookieConfig();
sessionCookieConfig.setHttpOnly(true);
}
}; } }
或者
@Configuration
//WebMvcConfigurerAdapter在2.0.*中已作废,有WebMvcConfigurer,WebMvcConfigurationSupport两种方案。
//public class WebSecurityConfig extends WebMvcConfigurerAdapter{
public class WebSecurityConfig implements WebMvcConfigurer {
//public class WebSecurityConfig extends WebMvcConfigurationSupport { @Bean
public ServletContextInitializer servletContextInitializer() {
return servletContext -> {
servletContext.setSessionTrackingModes(Collections.singleton(SessionTrackingMode.COOKIE));
SessionCookieConfig sessionCookieConfig=servletContext.getSessionCookieConfig();
sessionCookieConfig.setHttpOnly(true);
}; }
}
可以看到该段代码实现了以下接口
package org.springframework.boot.web.servlet; import javax.servlet.ServletContext;
import javax.servlet.ServletException; @FunctionalInterface
public interface ServletContextInitializer {
void onStartup(ServletContext servletContext) throws ServletException;
}