I'm serving up images from my servlet. The response content type is image/jpeg. I find that images requested from my servlet are not cached. How do I get them to be cached like file image requests normally are? I tried setting Cache-Control: public but to no avail.
相关问题
- Views base64 encoded blob in HTML with PHP
- Angular RxJS mergeMap types
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
The default servlet serving static content in containers like Tomcat doesn't set any cache control headers. You don't need write a servlet just for that. Just create a filter like this,
Whenever you want add cache control, just add the filter to the resources in web.xml. For example,
Ok.. looks like the default header fields should enable caching. I found a solution in another forum. Apparently, you need to explicitly set a content-length in the response. Wonder why though. I thought the HttpServletResponse would do that for us. Anyway, it worked like a charm and the image is getting cached nicely.
For example, if you want to cache them for 1 month:
(this is in a
Filter
that handles the*.jpg
pattern, for example)But images should be cached by default - check your filters and configurations to see if something isn't setting the cache parameters incorrectly.
You need to send the
ETag
,Last-Modified
andExpires
headers along the response. TheETag
represents the unique identifier of the file (usually composed based on a combination of filename, filesize and lastmodified timestamp). TheLast-Modified
represents the last modified timestamp of the file. TheExpires
header denotes how long the client is allowed to keep the file in cache. If the cache has been expired and theETag
orLast-Modified
are available, then the client will send aHEAD
request to check if the file needs to be renewed. If not, then theExpires
will just be postponed again accordingly.You can find here a servlet example which handles this all (and download resumes and automatic GZIP): FileServlet supporting resume and GZIP