Spring boot configure custom jsessionid for embedded server

佐手、 提交于 2019-12-18 11:22:15

问题


I want to configure my servlet context, such as setting a custom jsessionId key (see Changing cookie JSESSIONID name)

I believe I can use the SpringBootServletInitializer when running a WAR file, manipulating the servletContext in onStartup(). However, when I run on an embedded application server, using new SpringApplicationBuilder().run(), I don't know the best place to manipulate the servlet context.


回答1:


As of Spring Boot 1.3 you can simply set a configuration property;

Spring Boot 1.3, 1.4, 1.5

server.session.cookie.name = MYSESSIONID

Spring Boot 2.x

server.servlet.session.cookie.name = MYSESSIONID

A lot simpler than writing a configuration class.

See https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html for more session related properties.




回答2:


Declare a ServletContextInitializer bean in your application's configuration:

@Bean
public ServletContextInitializer servletContextInitializer() {
    return new ServletContextInitializer() {

        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            servletContext.getSessionCookieConfig().setName("yourCookieName");
        }
    };

}

Alternatively, your application class itself can implement 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");
    }

}



回答3:


with spring session , if you want to change cookie name ,you can do this

@Bean
public DefaultCookieSerializer defaultCookieSerializer(){
    DefaultCookieSerializer defaultCookieSerializer = new DefaultCookieSerializer();
    defaultCookieSerializer.setCookieName("mySessionId");
    return defaultCookieSerializer;
}

i find this in spring session source

spring-session-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);
}



回答4:


@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and()
    .csrf().disable();  
}

You can try this as it removes jsession id from URL



来源:https://stackoverflow.com/questions/25918556/spring-boot-configure-custom-jsessionid-for-embedded-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!