Wednesday, August 12, 2009

How can I avoid making multiple HTTP calls for content that hasn't changed? Is it possible to cache it? Is there a way to set this in the header?

This can be achieved by using a filter. You can setup the filter in your web.xml to intercept the response and edit the HTTP headers for the specified content type. An example filter could look like:

package com.xyz

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class CacheFilter implements javax.servlet.Filter {
FilterConfig filterConfig = null;

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

public void doFilter(ServletRequest req,
ServletResponse res,
FilterChain chain)
throws IOException, ServletException {
String sCache = filterConfig.getInitParameter("cache");

if(sCache != null){ ((HttpServletResponse)res).setHeader("Cache-Control", sCache);

}

chain.doFilter(req, res);
}

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


Now to set up this filter to act on all jpg requests you need to add the following to your web.xml file:


Cache
com.xyz.CacheFilter

cache
public, max-age=2592000



Cache
*.jpg



This filter will now instruct the client to store the specified content (jpg) in it's cache for 2592000 seconds from when this request was processed and no requests for this resource will be necessary till the time has elapsed.

No comments:

Post a Comment