Search code examples
servletscachingresponseno-cache

how to disable web page cache throughout the servlets


To no-cache web page, in the java controller servlet, I did somthing like this in a method:

public ModelAndView home(HttpServletRequest request, HttpServletResponse response) throws Exception {
    ModelAndView mav = new ModelAndView(ViewConstants.MV_MAIN_HOME);
    mav.addObject("testing", "Test this string");
    mav.addObject(request);
    response.setHeader("Cache-Control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    return mav;
}

But this only works for a particular response object. I have many similar methods in a servlet. And I have many servlets too.

If I want to disable cache throughout the application, what should I do? (I do not want to add above code for every single response object).


Solution

  • Why not do this via a filter?

    A filter is an object that can transform the header and content (or both) of a request or response. 

    ...

    The main tasks that a filter can perform are as follows:

    ...

    • Modify the response headers and data. You do this by providing a customized version of the response.

    Just register your Filter (class implementing the Filter interface) and modify your response within the doFilter method.


    EDIT: E.g.

    @WebFilter("/*")
    public class NoCacheFilter implements javax.servlet.Filter {
    
        @Override
        public void init(final FilterConfig filterConfig) throws ServletException {
        }
    
        @Override
        public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
    
            HttpServletRequest request = (HttpServletRequest)servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
    
            response.setHeader("Cache-Control", "no-cache, no-store");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
    
            filterChain.doFilter(request, response);
        }
    
        @Override
        public void destroy() {
        }
    }
    

    Note that the @WebFilter annotation will require Servlet 3.0, otherwise you can register it via your web.xml. This path of "/*", would apply to any path of your application, but could be narrowed in scope.