Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set tracking mode to cookie to remove appended session id, without using web.xml

I am setting up a completely java based spring app with no xml config :

public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{WebMvcConfigurer.class};
    }
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

and

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { mypackages })
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/static-assets/");
    }

    @Bean
    public ViewResolver viewResolver() {

        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

where do I put this, which used to be in my web.xml ?

 <session-config>
        <!-- Disables URL-based sessions (no more 'jsessionid' in the URL using Tomcat) -->
        <tracking-mode>COOKIE</tracking-mode>
    </session-config>
like image 981
NimChimpsky Avatar asked Nov 30 '22 04:11

NimChimpsky


2 Answers

you can do it as in below

public class WebConfig implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext)
            throws ServletException {
        HashSet<SessionTrackingMode> set = new HashSet<SessionTrackingMode>();
        set.add(SessionTrackingMode.COOKIE);
        servletContext.setSessionTrackingModes(set);

    }

}
like image 154
Bassem Reda Zohdy Avatar answered Dec 05 '22 11:12

Bassem Reda Zohdy


In a Spring Boot app, you can configure the mode using the application property server.session.tracking-modes.

In your application.properties add:

server.session.tracking-modes=cookie

Or if you use application.yml:

server:
  session:
    tracking-modes: 'cookie'

The Spring Boot autoconfiguration internally uses the same call to servletContext.setSessionTrackingModes which Bassem recommended in his answer.

UPDATE

In newer versions of Springboot, use

server.servlet.session.tracking-modes=cookie
like image 39
Michael Koch Avatar answered Dec 05 '22 12:12

Michael Koch