I am using spring-mvc 3.1.0.RELEASE and for some reason, mapping POST with query params and request body does not work.
Here is how my controller method looks:
@RequestMapping(method = POST, value = "/post-to-me/")
public void handlePost(
@RequestBody Content content,
@RequestParam("param1") String param1,
@RequestParam("param2") String param2
){
//do stuff
}
However, if I convert all the request params to path params, mapping works. Has anyone run into something similar?
Thanks!
EDIT:
"does not work" == 404 when I try doing, POST /post-to-me?param1=x¶m2=y
Can we use RequestBody and RequestParam together? nothing. So it fails with 400 because the request can't be correctly handled by the handler method.
The @PathVariable annotation is used for data passed in the URI (e.g. RESTful web services) while @RequestParam is used to extract the data found in query parameters. These annotations can be mixed together inside the same controller.
In http, put method can have request body but RequestParam Annotation doesn't work [SPR-7414] #12072.
@RequestParam is best for reading a small number of params. @ModelAttribute is used when you have a form with a large number of fields.
First, your POST url doen't match the controller method url, your POST url must be "/post-to-me/?param1=x¶m2=y" not "/post-to-me?param1=x¶m2=y"
Second, where did Content class come from?? I used a String and works fine for me
@RequestMapping(method = RequestMethod.POST, value = "/post-to-me/")
public void handlePost(@RequestBody String content,
@RequestParam("param1") String param1,
@RequestParam("param2") String param2, HttpServletResponse response) {
System.out.println(content);
System.out.println(param1);
System.out.println(param2);
response.setStatus(HttpServletResponse.SC_OK);
}
Note that I used HttpServletResponse to return a HTTP 200 code, but I think there is a better solution for return Http codes, check this: Multiple response http status in Spring MVC
Trailing slash at the end of your request mapping value might be the problem. Try:
@RequestMapping(method = RequestMethod.POST, value = "/post-to-me")
or send your POST request to POST /post-to-me/?param1=x¶m2=y
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With