[英]Servlet filter for browser caching?
有誰知道如何編寫一個servlet過濾器,它將在給定文件/內容類型的響應上設置緩存頭? 我有一個提供大量圖像的應用程序,我想通過讓瀏覽器緩存那些不經常更改的瀏覽器來減少托管它的帶寬。 理想情況下,我希望能夠指定內容類型,並在內容類型匹配時設置適當的標題。
有誰知道怎么做這個? 或者,甚至更好,有他們願意分享的示例代碼? 謝謝!
在你的過濾器中有這一行:
chain.doFilter(httpRequest, new AddExpiresHeaderResponse(httpResponse));
響應包裝器的位置如下:
class AddExpiresHeaderResponse extends HttpServletResponseWrapper {
public static final String[] CACHEABLE_CONTENT_TYPES = new String[] {
"text/css", "text/javascript", "image/png", "image/jpeg",
"image/gif", "image/jpg" };
static {
Arrays.sort(CACHEABLE_CONTENT_TYPES);
}
public AddExpiresHeaderResponse(HttpServletResponse response) {
super(response);
}
@Override
public void setContentType(String contentType) {
if (contentType != null && Arrays.binarySearch(CACHEABLE_CONTENT_TYPES, contentType) > -1) {
Calendar inTwoMonths = GeneralUtils.createCalendar();
inTwoMonths.add(Calendar.MONTH, 2);
super.setDateHeader("Expires", inTwoMonths.getTimeInMillis());
} else {
super.setHeader("Expires", "-1");
super.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
}
super.setContentType(contentType);
}
}
簡而言之,這會創建一個響應包裝器,在設置內容類型時,會添加過期標頭。 (如果需要,您可以添加所需的任何其他標題)。 我一直在使用這個過濾器+包裝器,它的工作原理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.