Last active
December 15, 2015 23:49
-
-
Save leszekgruchala/5343301 to your computer and use it in GitHub Desktop.
Http response wrapper for caching js, css and images for browsers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package eu.gruchala.web.wrapper; | |
import java.util.Arrays; | |
import java.util.Calendar; | |
import javax.servlet.http.HttpServletResponse; | |
import javax.servlet.http.HttpServletResponseWrapper; | |
/** | |
* Caches requests for all CSS, JS and images. | |
*/ | |
public class ResourcesCachingWrapper extends HttpServletResponseWrapper { | |
public static final String[] CACHEABLE_CONTENT_TYPES = new String[]{ | |
"text/css", "text/javascript", "application/javascript", | |
"image/png", "image/jpeg", "image/gif", "image/jpg" | |
}; | |
private static long MONTH = 0l; | |
static { | |
Arrays.sort(CACHEABLE_CONTENT_TYPES); | |
Calendar calendar = Calendar.getInstance(); | |
calendar.add(Calendar.MONTH, 1); | |
MONTH = calendar.getTimeInMillis(); | |
} | |
public ResourcesCachingWrapper(HttpServletResponse response) { | |
super(response); | |
} | |
@Override | |
public void setContentType(String contentType) { | |
if (contentType != null && Arrays.binarySearch(CACHEABLE_CONTENT_TYPES, contentType) > -1) { | |
super.setDateHeader("Expires", MONTH); | |
} else { | |
super.setHeader("Expires", "-1"); | |
super.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); | |
} | |
super.setContentType(contentType); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment