Monday 19 September 2011

REST with SpringMVC - Passing params in request body




Lately I was trying to pass parameters to a SpringMVC REST service. In order to do that I used @RequestParameter annotation in a method implementing my service.

Sample service method for updating user email could look as follows:
@RequestMapping(method=RequestMethod.POST, value="/user/{username}")
public String updateUser(HttpServletResponse response,
@PathVariable("username") String username,
@RequestParameter("email") String email)
{
// UPDATE USER EMAIL HERE
}
As you can see expected request parameter is defined as method parameter and annotated with @RequestParameter specifying the parameter name. Originally it seemed that this approach only works when parameters are passed as URL params but doesn't when params are passed in request body i.e. the following HTTP request would work:
POST http:///user/?email=test%40example.com HTTP/1.1
Host:
(...)
whereas the following would not:
POST http:///user/ HTTP/1.1
Host:
(...)

email=test%40example.com

When I start googling for this issue I found several opinions stating that this is a known bug and suggesting some workarounds e.g. using @RequestBody annotation and manually extracting parameter values from the body string.

However, the issue disappears if you specify the content type as one of the request headers:
Content-Type: application/x-www-form-urlencoded
After I added this to my http request both url and body params are captured with @RequestParameter annotation.

No comments: