1 24 package org.riotfamily.common.web.filter; 25 26 import java.io.IOException ; 27 import java.util.regex.Pattern ; 28 29 import javax.servlet.FilterChain ; 30 import javax.servlet.ServletException ; 31 import javax.servlet.ServletRequest ; 32 import javax.servlet.ServletResponse ; 33 import javax.servlet.http.HttpServletRequest ; 34 import javax.servlet.http.HttpServletResponse ; 35 36 import org.riotfamily.common.util.FormatUtils; 37 import org.riotfamily.common.web.util.ServletUtils; 38 import org.springframework.web.filter.GenericFilterBean; 39 40 52 public class CacheStampedResourcesFilter extends GenericFilterBean { 53 54 public static final String DEFAULT_EXPIRATION = "1M"; 55 56 public static final Pattern DEFAULT_PATTERN = 57 Pattern.compile("(/\\d{14}/)|(\\?[0-9]+$)"); 58 59 private static final String EXPIRES_HEADER = "Expires"; 60 61 private Pattern stampPattern = DEFAULT_PATTERN; 62 63 private String expiresAfter = DEFAULT_EXPIRATION; 64 65 private long expires; 66 67 public void setExpiresAfter(String expiresAfter) { 68 this.expiresAfter = expiresAfter; 69 } 70 71 public void setStampPattern(Pattern stampPattern) { 72 this.stampPattern = stampPattern; 73 } 74 75 protected void initFilterBean() throws ServletException { 76 expires = System.currentTimeMillis() 77 + FormatUtils.parseMillis(expiresAfter); 78 } 79 80 public final void doFilter(ServletRequest request, ServletResponse response, 81 FilterChain filterChain) throws IOException , ServletException { 82 83 doFilterInternal((HttpServletRequest ) request, 84 (HttpServletResponse ) response, filterChain); 85 } 86 87 protected void doFilterInternal(HttpServletRequest request, 88 HttpServletResponse response, FilterChain filterChain) 89 throws ServletException , IOException { 90 91 if (isStamped(request)) { 92 response.setDateHeader(EXPIRES_HEADER, expires); 93 } 94 filterChain.doFilter(request, response); 95 } 96 97 protected boolean isStamped(HttpServletRequest request) { 98 String url = ServletUtils.getRequestUrlWithQueryString(request); 99 return stampPattern.matcher(url).matches(); 100 } 101 } 102 | Popular Tags |