How to Control HTTP Caching in Java Web application using Spring MVC Framework

One of the standard requirement in a secure Java web application is to disallow the back button of the browser or invalid the session if the user hit the back button of the browser. You might have seen this behavior while doing online banking or net banking, almost all the banks don't allow you to use the browser's back button. Your session gets terminated as soon as you hit the back button, and you have to log in again to do any transaction. Btw, Have you ever checked some situation on your Java web application like, if you pressed the back button of your browser after logging in, what happened? You will find that the browser takes you to the previous page.


This happens because your browser usually doesn't send another GET request to the server. Instead, it views the web page from locally cached responses. This is called browser caching/HTTP caching, it could happen not only on a login page but on any page. This behavior is actually controlled by the Cache-Control header of the HTTP response.

Ideally, your web application should redirect you to your after-logged-in-page (usually the Homepage) instead of showing the login form page or simply just invalidate the session if security doesn't permit that.

Anyway, in this article, I'll tell you how you can instruct the browser to not cache the dynamic content in its local cache by using the Cache-Control  header and how to set that using the Spring MVC framework.

Btw, if you are new to Spring framework and Spring MVC then I also suggest you first go through a comprehensive course like Spring Framework 5: Beginner to Guru to learn basics. This will help you to use Spring MVC better.




How to set Cache-Control header using Spring Framework?

If you are developing your Java Web application using the Spring MVC framework (if you are not, then you should) provides an easy way to stop dynamic content caching at Browser. You need to declare a WebContentInterceptor bean and define its properties in your servlet context file to prevent browsers from caching dynamic content.

The WebContentInterceptor is a Handler Interceptor in the Spring MVC framework that checks the request and prepares the response. It checks for supported methods and a required session and applies the specified CacheControl builder. This interceptor is mainly intended for using checks and preparations for a set of controllers mapped by HandlerMapping.

Here is a sample configuration you can use to prevent browsers from caching dynamic content, e.g. content generated by Servlet, JSP, or any other dynamic technology:

<!--Prevent browsers from caching contents except for the static resources content-->
    <mvc:interceptors>
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"
              p:paramName="lang"/>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <mvc:exclude-mapping path="/resources/**"/>
            <bean id="webContentInterceptor" 
                  class="org.springframework.web.servlet.mvc.WebContentInterceptor">
                <property name="cacheSeconds" value="0"/>
                <property name="useExpiresHeader" value="true"/>
                <property name="useCacheControlHeader" value="true"/>
                <property name="useCacheControlNoStore" value="true"/>
            </bean>
        </mvc:interceptor>
    </mvc:interceptors>

This configuration will intercept all request because mapping path is a wildcard which will match all request path, but then all the request which has /resources in the URL will be excluded. This means you need to put your static resources, like HTML, JavaScript, images into that path.

Most of the websites use this tag for HTTP caching, and here is one of the example from StackOverFlow, programmers most loved site:

How to set Cache-Control header using Spring Framework?

That's all about how to disable local content caching using the Spring framework. This is an essential feature from a security point of view, which the Spring MVC framework provides out-of-the-box. You can also control and customize the behavior by setting the value which your application needs, e.g. you can specify the number of seconds before the cache expires.

If you want to learn more about security in a web application, I suggest you join Learn Spring Security Masterclass by Eugen Paraschiv of Baeldung.


Further Reading
Spring Framework 5: Beginner to Guru
Spring Master Class - Beginner to Expert
How Spring MVC framework Works Internally
Top 5 Courses to learn Spring Boot in Depth
How to enable Spring Security in Java Web Application
10 Spring Courses to learn Microservices
How to pass Spring Web Application Developer Certification
Top 5 Courses to learn Core Spring in Depth
23 Spring MVC Interview Questions and Answers
Spring and Hibernate for Beginners

Thanks for reading this article, if you like this article, then please share with your friends and colleagues. If you have any questions or feedback, then please drop a comment, and I'll try to find an answer for you.

P.S. - If you want to learn how to develop RESTful Web Service using Spring MVC in-depth, I suggest you join the REST with Spring certification class by Eugen Paraschiv. One of the best courses to learn REST with Spring MVC.

No comments:

Post a Comment