Monday, 18 July 2011

Using Spring's @RequestBody Annotation

Spring MVC has some handy-dandy annotations for mapping http data into your controller’s handler methods. So far, I’ve looked at, amongst others, @RequestParam and @PathVariable. Today, I’m looking at @RequestBody. This annotation can be applied to one of your handler method arguments to map the request body information to that argument. By ‘request body’ I mean the whole of the HTTP request unprocessed. The mapping to one of your handler method arguments is done internally by Spring and according to Spring’s documentation the request can be mapped in to a number of formats, including a String - which I’m looking at today as it’s one of the simplest mappings.

In order to demonstrate this, I first set up a page that’ll POST a request to a controller.

<form:form method="POST" action="requestbody">
 <input type="submit" name="action" id="request_body_test" value="<spring:message code="label.request.body"/>"  />
 <input type="hidden" id="age" name="age" value="23" />
 <input type="hidden" id="gender" name="gender" value="male" />

In the above HTML, the value of 'label.request.body' = 'Test the @RequestBody Annotation, map to a String'. Also note that I’ve used a Http POST above as GET is not supported.

The next step is to create a controller handler method, annotating one of the arguments appropriately. In this simple example, I’m getting hold of the request body and echoing it back to the browser.

public class MiscAnnotationsController {

@RequestMapping(value = "/requestbody", method = RequestMethod.POST)
public void writeRequestBody(@RequestBody String body, Writer writer) throws IOException {

// This will be the contents of the next page you see
All that’s left to do now, is to press the form’s submit button, which delivers you to a page containing the following:


No comments: