Tuesday, 19 July 2011

Using Spring's @ResponseBody Annotation

Yesterday’s blog demonstrated how to use the @RequestBody annotation to map the HTTP request into an argument of your controller’s handler method. Today, I’m demonstrating its counterpart: @ResponseBody.

The @ResponseBody is used to map the return value from your controller’s handler method directly into the body of your Http response.

This works with a simple Http GET, so to test your controller, you’ll need a page containing the following link:

<a href="responsebody"><spring:message code="label.response.body"/></a>

...where ‘label.response.body’ = ‘Test the @ResponseBody Annotation’.

Next, write a controller that’ll return some text as the http response body. In the code below, I’m returning "<h2>This should be the response body</h2>", which my browser will display in large black letters.

@Controller
public class MiscAnnotationsController {

 
@RequestMapping(value = "/responsebody", method = RequestMethod.GET)
 
@ResponseBody
 
public String handleResponseBody() {

   
return "<h2>This should be the response body</h2>";
 
}
}

This is fully documented by Spring (and there isn’t much to it). Note that I’ve used String as the return type, but Spring comes with a default set of Http Message converters to support different return types.

You may ask why you need this annotation... well it’s used to support web 2 technologies such as AJAX, where your response will contain a lump of XML or JSON.

1 comment:

Priyanka said...

when i used spring tiles also in same application.then how to handle with spring @ResponseBody.?