Spring-Framework-Logo

We live in a nice time, when you can develop a Spring application using java based configuration. No redundant XML code any more, just pure java code. In this article I want to discuss a popular topic about session management in Spring applications. If to be more precise I’m going to talk about a session timeout in java configuration style.

So in one of my previous blog posts I’ve already said how to manage a lifetime of session. But that solution implies usage of web.xml file, which is not required for java based configs. Because its role plays a class which extends AbstractAnnotationConfigDispatcherServletInitializer class. Frequently it looks something like this:

import javax.servlet.Filter;

import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return null;
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class<?>[] { WebAppConfig.class };
	}

	@Override
	protected String[] getServletMappings() {
		return new String[] { "/" };
	}

	@Override
	protected Filter[] getServletFilters() {
		return new Filter[] { new HiddenHttpMethodFilter() };
	}

}

I’ve written a lot about usage of such configurations, but here we should pay extra attention to classes which AbstractAnnotationConfigDispatcherServletInitializer extends. I talk about the AbstractDispatcherServletInitializer class. In its turn it has onStartup(ServletContext servletContext) method. Its purpose is to configure a ServletContext with any servlets, filters, listeners context-params and attributes necessary for initializing this web application.

Directly in this place it’s a good time to recall about the HttpSessionListener interface. As you have already guessed in an implementation of this interface we are able to manage each just created session a an application. For example we can set a maximum inactive interval equal to 5 minutes:

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        System.out.println("==== Session is created ====");
        event.getSession().setMaxInactiveInterval(5*60);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        System.out.println("==== Session is destroyed ====");
    }
}

In order to apply this session management changes into our java based configurations, we have to add a following code snippet to Initializer class:

...
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        servletContext.addListener(new SessionListener());
    }
...

That’s all java geeks, enjoy coding.

About The Author

Mathematician, programmer, wrestler, last action hero… Java / Scala architect, trainer, entrepreneur, author of this blog

  • Changkeun You

    Thanks Good Sample Sample Sources..

  • Changkeun You

    Thanks Good Sample Sources..

  • veggen

    I appreciate your article but have to opine on the whole “OMG! No XML” fad. How is writing a whole class and hiding configs into code better than:

    20

    added to a standard (thus known to all) config file?

    • Charles

      These days, XML is being replaced more and more with Java Config. XML only brings noise to developer’s work. Maintaining separate configuration files is already a time consuming task. Imagine when the change language changes all the time (java, gradle build script, xml, etc.). The more I can leverage my knowledge of Java, the happier I am.

      The bottom line is that it comes down to personal preference. Some people prefer XML over Java Config, as some other hates XML, like me for instance.

      Both solutions work and provide the same results…

  • hntehelang

    Thanks man. May I confirm that using -1 will mean the session won’t end until the browser is closed.

  • Raby Chaabani

    hi is there a way to pass a value to the http listener for the timeout instead of a static value ?

  • Host Vedant

    How can i pass session timeout value from property file.
    getting nullpointer exception in getting the sessionTimeOut value from property file.

Close