How to set no-cache headers in a Java EE application’s response (using a Spring controller)

Sometimes when you do a request to a Java service you will need to add some custom headers in the response, for example, today I was creating a service to get the current logged user data and I realized one client was storing (creating a cache) the response and sometimes the service was not working as expected.

java

So, in my case I was using Spring MVC to create a custom XML response I wanted to add a no-cache header, for that reason I spent some time to figure out which is the right way to do it, please let me explain how you can do that easily!

1) Following is an example of a Java method that contains Spring and JAXB annotations to create a custom XML and set custom headers in the response:

	@RequestMapping(method ={RequestMethod.GET, RequestMethod.POST}, produces="application/xml")
	public @ResponseBody UserProfileResponse getUserProfileInXML(HttpServletRequest request, HttpServletResponse response) {

		// UserProfileResponse and UserProfileService are MY custom classes, but you can retrieve any class you want!
		UserProfileResponse profileResponse = new UserProfileResponse();
		UserProfileService service = UserProfileService.getInstance();	// A singleton class
		Principal principal = (Principal) request.getUserPrincipal();

		if (principal != null) {
			profileResponse.setUserProfile( service.getUserProfile(principal.getName()) );
		}

		// Setting response's headers
		response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
		response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
		response.setDateHeader("Expires", 0); // Proxies.

		return profileResponse;
	}

2) The important lines in previous code are:

// Setting response's headers
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setDateHeader("Expires", 0); // Proxies.

Because they set custom response’s headers to establish a no-cache configuration.

3) Now, just to test we could do a normal request in a browser and we can see the headers:

no-cache-headers-response

As you can see, the headers were set correctly.

That’s it!

Be happy with your code!

Leave a Reply

Your email address will not be published. Required fields are marked *