Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable Tomcat session persistence in Spring Boot via Manager pathname?

Tags:

In Tomcat there is a well known configuration option in conf/context.xml to disable session persistence:

<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<Manager pathname="" />

When uncommented as shown here, the applied implementation of org.apache.catalina.Manager (e.g. org.apache.catalina.session.StandardManager) does not have a pathname to tell it where to store sessions to the disk, and thus it does not write session files to disk (e.g. on shutdown), which is what we want.

In other words, this disables the standard Tomcat feature to sustain sessions through server restart.

How can the same be achieved in Spring Boot with embedded Tomcat?

Perhaps the Manager object can somehow be obtained to set the property pathname to null?

like image 590
jamesbond007 Avatar asked Nov 25 '14 15:11

jamesbond007


People also ask

What is Tomcat persistence manager?

PersistentManager. In addition to the usual operations of creating and deleting sessions, a PersistentManager has the capability to swap active (but idle) sessions out to a persistent storage mechanism, as well as to save all sessions across a normal restart of Tomcat.

Which file is used to manage the persistent sessions in Tomcat?

xml file. It will then use the store to maintain the session on each http request.

How do I get active sessions in Tomcat?

To find out the number of active sessions, you can use Tomcat's internal statistics that can be accessed using JMX (Java Management Extension). You can also use a JavaEE applications monitoring tool, such as JavaMelody, which helps you monitor Java or Java EE applications in QA and production environments.


2 Answers

You can use a TomcatContextCustomizer to access the manager and apply the necessary configuration:

@Bean
public EmbeddedServletContainerFactory servletContainer() {
    TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
    tomcat.addContextCustomizers(new TomcatContextCustomizer() {

        @Override
        public void customize(Context context) {
            if (context.getManager() instanceof StandardManager) {
                ((StandardManager) context.getManager()).setPathname("");
            }
        }
    });
    return tomcat;
}
like image 57
Andy Wilkinson Avatar answered Sep 29 '22 07:09

Andy Wilkinson


This behavior can be customized via application.properties:

server.servlet.session.persistent=false # Whether to persist session data between restarts.

Session persistence is disabled by default in Spring Boot 2.x.

like image 28
Thomas Avatar answered Sep 29 '22 09:09

Thomas