Performance: Content type negotiation
Content type negotiation affects how quickly the server can respond with the correct data format, impacting initial response time and perceived page load speed.
@GetMapping(value = "/data", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) public ResponseEntity<?> getData() { // Spring automatically negotiates content type return ResponseEntity.ok(dataObject); }
public ResponseEntity<String> getData(HttpServletRequest request) {
String accept = request.getHeader("Accept");
if (accept != null && accept.contains("application/json")) {
return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(jsonData);
} else if (accept != null && accept.contains("application/xml")) {
return ResponseEntity.ok().contentType(MediaType.APPLICATION_XML).body(xmlData);
} else {
return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).build();
}
}| Pattern | CPU Usage | Response Time | Error Risk | Verdict |
|---|---|---|---|---|
| Manual header parsing and response selection | High (extra CPU cycles) | Higher (~10-20ms slower) | Higher (manual errors possible) | [X] Bad |
| Spring built-in content negotiation | Low (optimized internal handling) | Lower (faster response) | Low (framework tested) | [OK] Good |
@GetMapping(value = "/info", produces = {"application/json", "application/xml"})
public Data getInfo() {
return new Data("Spring", 5);
}
What will happen if the client sends an HTTP Accept header with value application/xml?@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorParameter(true)
.parameterName("format")
.defaultContentType(MediaType.APPLICATION_JSON)
.mediaType("xml", MediaType.APPLICATION_XML)
.mediaType("json", MediaType.APPLICATION_JSON);
}
What is the likely problem if a client requests /api/data?format=txt??type= instead of the default ?format=. Which code snippet correctly achieves this?Pass the test and this pattern moves unknown