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?

Byron Tymvios

 

 

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:

<filter>
  <filter-name>Cache</filter-name>
  <filter-class>com.xyz.CacheFilter</filter-class>
  <init-param>
    <param-name>cache</param-name>
    <param-value>public, max-age=2592000</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>Cache</filter-name>
  <url-pattern>*.jpg</url-pattern>
</filter-mapping>

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.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact