java
35 lines · 6 steps
HTTP caching with ETags in Spring
A shallow ETag filter plus Cache-Control headers cut bandwidth by letting clients revalidate and reuse product responses.
Explained by
highlit
1@Configuration
2public class WebConfig {
3
4 @Bean
5 public FilterRegistrationBean<ShallowEtagHeaderFilter> shallowEtagHeaderFilter() {
6 FilterRegistrationBean<ShallowEtagHeaderFilter> registration =
7 new FilterRegistrationBean<>(new ShallowEtagHeaderFilter());
8 registration.addUrlPatterns("/api/products/*");
9 registration.setName("etagFilter");
10 registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 10);
11 return registration;
12 }
13}
14
15@RestController
16@RequestMapping("/api/products")
17class ProductController {
18
19 private final ProductRepository productRepository;
20
21 ProductController(ProductRepository productRepository) {
22 this.productRepository = productRepository;
23 }
24
25 @GetMapping("/{id}")
26 public ResponseEntity<ProductView> getProduct(@PathVariable Long id) {
27 Product product = productRepository.findById(id)
28 .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
29
30 ProductView body = ProductView.from(product);
31 return ResponseEntity.ok()
32 .cacheControl(CacheControl.maxAge(Duration.ofMinutes(5)).cachePublic())
33 .body(body);
34 }
35}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A shallow ETag filter hashes the rendered response body so unchanged content returns 304 without re-sending it.
- 2Scoping a FilterRegistrationBean to a URL pattern keeps expensive filters off routes that don't need them.
- 3Cache-Control and ETag work together: one sets freshness lifetime, the other enables cheap revalidation after it expires.
Related explainers
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
java
public final class EncodingDetector { public enum Encoding { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN
Detecting text encoding from raw bytes in Java
byte-manipulation
encoding-detection
bitwise-operations
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/http-caching-with-etags-in-spring-explained-java-e619/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.