Home > Uncategorized > Servlet Filter to prevent No-Cache

Servlet Filter to prevent No-Cache

In one of the posts, I had talked about IE caching AJAX calls. To solve this issue , you would have to modify response such that it informs browser not to cache the data coming from this server.

I am explaining it in plain old fashioned way of ServletFilter.

Below is the code for ServletFilter.

public class NoCacheFilter implements Filter {

private FilterConfig filterConfig = null;

public void init(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}

public void destroy() {
this.filterConfig = null;
}

/**
* Modifies the response. Sets the appropriate headers
* and invoke the next filter in the chain:
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {

HttpServletResponse httpResponse = (HttpServletResponse) response;

httpResponse.setHeader(“Cache-Control”, “No-cache”);
httpResponse.setDateHeader(“Expires”, 0);
httpResponse.setHeader(“Pragma”, “No-cache”);
chain.doFilter(request, response);

}
}

This is helpful for browsers like IE which Cache your data by default and do not display fresh data. This is one of the situations when you are working with JSON REST web services in which you might to pull and display fresh data.

Categories: Uncategorized Tags: