开发者

response.setDateHeader() - caching not working

开发者 https://www.devze.com 2023-02-15 19:36 出处:网络
I want .png files in my web page to be cached. I added the following entry in web.xml <filter> <filter-nam开发者_高级运维e>ContentFilter</filter-name>

I want .png files in my web page to be cached. I added the following entry in web.xml

 <filter>  
    <filter-nam开发者_高级运维e>ContentFilter</filter-name>  
    <filter-class>filters.ContentFilter</filter-class>  
   <init-param>  
       <description>Add an Expires Header</description>  
       <param-name>expiryDate</param-name>  
       <param-value>Fri, 30 Apr 2021 20:00:00 GMT</param-value>  
   </init-param>  
   </filter>
<filter-mapping>  
   <filter-name>ContentFilter</filter-name>  
  <url-pattern>*.png</url-pattern>  
</filter-mapping>

Setting expiryDate field value in the following manner in init()

String expiryDateStr = filterConfig.getInitParameter("expiryDate");
    SimpleDateFormat format = new SimpleDateFormat(
            "EEE, d MMM yyyy HH:mm:ss Z");
    try {
        Date d = format.parse(expiryDateStr);
        expiryDate = d.getTime();
    } catch (ParseException e) {
        logger.error(e.getMessage(), e);
    }

The doFilter() is :

public void doFilter(ServletRequest req, ServletResponse res,
        FilterChain filChain) throws IOException, ServletException {
    logger.debug("doFilter()");
    logger.info(((HttpServletRequest)req).getRequestURL().toString());
    filChain.doFilter(req, res);
    if (res instanceof HttpServletResponse) {
        HttpServletResponse response = (HttpServletResponse) res;
        logger.info(((HttpServletRequest)req).getRequestURL().toString());
        response.setDateHeader("Expires", expiryDate); 
    }
}

My problem is, whenever i refresh the web page in the browser, the client keeps requesting the .png files. Guess my filter is not working. Is this configuration correct?


Looking at your code, a likely culprit is that you're setting the response header after the request has been processed by the servlet. It's too late to add a header at the point, the response data is already sent.

Move the response.setDateHeader to before the filChain.doFilter, and the header should be sent.

Having said that, this stuff is notoriously tricky to get right. Browsers have all sort of different behaviours for HTTP caching, and sending what you think is the right header doesn't always have the effect you're looking for.

Try using an HTTP header sniffing tool (like the excellent "Live HTTP Headers" plugin for firefox) to see what's actually going back and forth.


'Expires' date should not be more than one year in future. See Section 14.21 Expires in http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

To mark a response as "never expires," an origin server sends an Expires date approximately one year from the time the response is sent. HTTP/1.1 servers SHOULD NOT send Expires dates more than one year in the future.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号