@RequestBody and @ResponseBody annotations

When using @ResponseBody annotation, developer is still able to explicitly set the content type that the method returns (JSON is used as a content type by default). For that, the @RequestMapping’s produces attribute can be used. Annotations like @PostMapping, @GetMapping, etc. define aliases for that parameter. Compare two code snippets below :

@PostMapping(value = "/content", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseTransfer postResponseJsonContent() {
    return new ResponseTransfer("JSON Content!");
}
...
@PostMapping(value = "/content", produces = MediaType.APPLICATION_XML_VALUE)
@ResponseBody
public ResponseTransfer postResponseXmlContent() {
    return new ResponseTransfer("XML Content!");
}

Note that depending on the value of an ‘Accept’ parameter sent in the request’s header, different responses will be gotten. Let’s see it in action :

curl -i \ 
-H "Accept: application/json" \ 
-H "Content-Type:application/json" \ 
-X POST "https://localhost:8080/.../content"

The above CURL command returns a JSON response

HTTP/1.1 200
Content-Type: application/json
Transfer-Encoding: chunked
Date: Thu, 20 Feb 2020 19:43:06 GMT
 
{"text":"JSON Content!"}

And if ‘Accept’ parameter is changed :

curl -i \
-H "Accept: application/xml" \
-H "Content-Type:application/json" \
-X POST "https://localhost:8080/.../content"

The content of response will be XML :

HTTP/1.1 200
Content-Type: application/xml
Transfer-Encoding: chunked
Date: Thu, 20 Feb 2020 19:43:19 GMT
 
<ResponseTransfer><text>XML Content!</text></ResponseTransfer>

Note that JSON serializer is a part of classpath due to being present as a transitive dependency in spring-related dependencies (spring-boot-starter-web in particular). But in many cases XML serializer (jackson-dataformat-xml) must be defined explicitly in dependencies section (assuming it is a Maven project).

Previous

Leave a Reply

Your email address will not be published. Required fields are marked *