Wednesday, 20 July 2011

Using the Spring ResponseEntity Class

Spring’s @ResponseBody annotation, which I talked about yesterday, covers scenarios where you want absolute control over what’s passed back to your client in the Http response body. There are times, however, where you’ll want absolute control over both the Http response body and the response header.

In this case, you should use Spring’s ResponseEntity class as the return type of your controller’s handler method. In order to test this out, you first need a web page that contains the following link:

<a href="responseentity">Test...</a>

Next, add the following test method to one of your controllers:

public ResponseEntity<String> handleResponseEntity() {

HttpHeaders responseHeaders = new HttpHeaders();
("HeaderKey", "HeaderData");
return new ResponseEntity<String>(
"<i>This is</i> the <h2>Page value</h2> (ResponseBody)", responseHeaders,

You can see that the code above first creates an HttpHeaders object and adds some data to it. It then returns a new ResponseEntity object containing the HttpHeaders object, together with some sample HTML. It also sets the http status to HttpStatus.CREATED, which is http code 201 and means that the server has created a new resource.

A with @ResponseBody Spring uses its message converters to convert your response entity object into the http response that’s passed down the wire. Spring also document this class, but again, it’s very brief.

No comments: