[英]Spring boot configure custom jsessionid for embedded server
我想配置我的servlet上下文,例如设置自定义jsessionId键(请参阅更改cookie JSESSIONID名称 )
我相信我可以在运行WAR文件时使用SpringBootServletInitializer
,在onStartup()
操作servletContext
。 但是,当我在嵌入式应用程序服务器上运行时,使用new SpringApplicationBuilder().run()
,我不知道操作servlet上下文的最佳位置。
从Spring Boot 1.3开始,您只需设置配置属性即可;
Spring Boot 1.3,1.4,1.5
server.session.cookie.name = MYSESSIONID
Spring Boot 2.x
server.servlet.session.cookie.name = MYSESSIONID
比编写配置类简单得多。
有关更多与会话相关的属性,请参阅https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html 。
在应用程序的配置中声明一个ServletContextInitializer
bean:
@Bean
public ServletContextInitializer servletContextInitializer() {
return new ServletContextInitializer() {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.getSessionCookieConfig().setName("yourCookieName");
}
};
}
或者,您的应用程序类本身可以实现ServletContextInitializer
:
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application implements ServletContextInitializer {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.getSessionCookieConfig().setName("yourCookieName");
}
}
使用春季会话,如果要更改cookie名称,可以执行此操作
@Bean
public DefaultCookieSerializer defaultCookieSerializer(){
DefaultCookieSerializer defaultCookieSerializer = new DefaultCookieSerializer();
defaultCookieSerializer.setCookieName("mySessionId");
return defaultCookieSerializer;
}
我在春季会议中找到了这个
弹簧会话1.2.1.RELEASE-sources.jar!/org/springframework/session/config/annotation/web/http/SpringHttpSessionConfiguration.java
@Autowired(required = false)
public void setCookieSerializer(CookieSerializer cookieSerializer) {
this.defaultHttpSessionStrategy.setCookieSerializer(cookieSerializer);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and()
.csrf().disable();
}
你可以试试这个,因为它从URL中删除了jsession id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.