Master HTTP Caching: Using Last-Modified, ETag, Expires, and Cache-Control
This article explains how to effectively reduce server load and bandwidth by leveraging HTTP caching mechanisms such as Last-Modified, ETag, Expires, and Cache-Control headers, including practical servlet code examples and browser behavior details.
Proper use of HTTP caching can dramatically lower server load and network bandwidth, making it essential to understand the HTTP caching protocol.
1. Use the Last-Modified header
On the first request, the server returns a Last-Modified header with a GMT timestamp, e.g., Wed, 22 Jul 2009 07:08:07 GMT. In a servlet you can add it with: response.addDateHeader("Last-Modified", date.getTime()); The corresponding request header is If-Modified-Since. The server compares this value with the resource's last modification time and returns a 304 Not Modified response if unchanged. To read the request header in a servlet:
long last = request.getDateHeader("If-Modified-Since");2. Use the ETag header
When timestamps are insufficient, an ETag can be generated from the content (e.g., using CRC32 or MD5). The response includes the ETag header, and the client sends it back in If-None-Match. If they match, the server returns 304 without a body.
3. Use the Expires header
The Expires header tells the browser not to request the resource until the specified time, allowing the content to be served from the local cache. In a servlet you can set it with:
response.addDateHeader("Expires", date.getTime());4. Use max‑age in Cache‑Control
The max-age directive specifies how many seconds the response is considered fresh. Example: response.addHeader("Cache-Control", "max-age=10"); If you need additional directives (e.g., private), combine them in a single header: response.addHeader("Cache-Control", "private, max-age=10"); Summary Last-Modified and ETag still require a request to the server, but only a 304 status is returned when the content is unchanged. Expires and max-age allow the browser to serve the resource directly from its cache without contacting the server. Note that a manual refresh (Ctrl+F5) bypasses all caches.
Useful HTTP monitoring tools
Firefox: httpfox, Live HTTP Header
Internet Explorer: HttpWatch, IEHttpHeader
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
