How do I write a filter which will appropriately cache static resources as recommended by Google
If you mean with JSF resources the files in /resources
folder which are fully handled by JSF builtin resource handler (and thus all referenced via <h:outputStylesheet>
, <h:outputScript>
, <h:graphicImage>
, #{resource}
and thus not via the plain HTML way), then you don't need to homegrow a filter for the job. The only thing which you need to do to satisfy Google recommendations is to set the Expires
date a bit further in the future. It namely defaults to 7 days (604800000 milliseconds) while performance testing tools like Google Page Speed and Yahoo YSlow recommends a minimum of 30 days (2592000000 milliseconds).
In Mojarra, you can set it with the following context parameter in web.xml
:
<context-param>
<param-name>com.sun.faces.defaultResourceMaxAge</param-name>
<param-value>2592000000</param-value> <!-- 30 days -->
</context-param>
And in MyFaces with the following one:
<context-param>
<param-name>org.apache.myfaces.RESOURCE_MAX_TIME_EXPIRES</param-name>
<param-value>2592000000</param-value> <!-- 30 days -->
</context-param>
Is it sufficient to create a filter which sets the last-modified date to some static date (this will change every time the server restarts)?
You don't and shouldn't need to set the Last-Modified
. The JSF resource handler already does that automatically. If you'd like to force reloading by resources because you changed them, then use resource library versioning. See also What is the JSF resource library for and how should it be used?
Note that changing it everytime the server restarts makes no sense as the Expires
header would still keep telling the browser to re-test the validity of the cache after a certain period only. Until the browser actually requests the resource, the browser would never notice the change in the Last-Modified
of a resource. The only thing which forces the browser hard to re-request the resource fully is a change in the URL, usually achieved by a changed query string parameter value. The JSF resource library versioning does exactly that.
Also note that the OmniFaces CombinedResourceHandler
uses the resource's last modified timestamp as "resource version" in the query string instead of the resource library version. So if you're using that, you don't necessarily need resource library versioning mechanism.
The link above seems to suggest you need to specify Expires or Cache-Control. Why is that necessary?
The Expires
header tells the browser when to re-test the validity of the cached resource by a conditional GET request. So, until that time the browser won't do that and will keep using the one in the cache. The Cache-Control
tells the browser which caching strategy to use. Note that when it's set to e.g. no-cache
instead of public
, then the Expires
header would have no effect. Also note that the absence of Cache-Control
header implies public
(as done by JSF resources).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…