Configuring HTTP Session timeout in Spring Boot applications

You can configure HTTP Session Timeout for Spring Boot Applications in two ways:

Configuring Session Timeout in application.properties

The simplest option is to include in your application.properties the parameter server.servlet.session.timeout. For example:

server.servlet.session.timeout=60s

Also note that Tomcat will not allow you to set the timeout any less than 60 seconds.

Configuring Session Timeout Programmatically

Let’s say we want that our HttpSession last only two minutes. To make this happen, we can add to our WebConfiguration class an EmbeddedServletContainerCustomizer Bean with the following content:

@Configuration
public class WebConfiguration {
  @Bean
  public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer() {
    return new EmbeddedServletContainerCustomizer() {
      @Override
      public void customize(ConfigurableEmbeddedServletContainer container) {
        container.setSessionTimeout(2, TimeUnit.MINUTES);
      }
    };
  }
}

And here is a shortcut using Java 8 and lambda expression:

  public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer() {
    return (ConfigurableEmbeddedServletContainer container) -> {
      container.setSessionTimeout(2, TimeUnit.MINUTES);
    };
  }

During the application startup, Spring Boot autoconfiguration detects the EmbeddedServletContainerCustomizer and invokes the customize(…) method, passing the reference to a servlet container.