Response.setDateHeader () - caching does not work

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

<filter> <filter-name>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> 

Set the value of expiryDate in the following order to 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); } 

doFilter ():

 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 that whenever I refresh a webpage in a browser, the client keeps requesting .png files. Guess my filter is not working. Is this configuration correct?

+4
source share
2 answers

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

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

Having said that, this material, as you know, is difficult to do correctly. Browsers have all sorts of behaviors for HTTP caching, and sending what you think is the right header doesn't always have the effect you're looking for.

Try using the HTTP header sniffing tool (for example, the excellent Live HTTP Headers "plugin for firefox) to see what actually happens back and forth.

+2
source

The expiration date should not exceed one year in the future. See Section 14.21 Expires at http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

To mark the response as β€œnever expires,” the origin server sends an expiration date of approximately one year from the time the response is sent. HTTP / 1.1 servers MUST NOT send expiration dates of more than one year in the future.

+2
source

Source: https://habr.com/ru/post/1343153/


All Articles