Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using both @RequestBody and @RequestParam together in spring mvc3

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&param2=y

like image 453
Ajay Avatar asked Apr 18 '12 19:04

Ajay


People also ask

Can we use @RequestBody and @RequestParam together?

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.

Can we use RequestParam and PathVariable together?

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.

Can we use @RequestParam in put method?

In http, put method can have request body but RequestParam Annotation doesn't work [SPR-7414] #12072.

What is the difference between @RequestParam and ModelAttribute?

@RequestParam is best for reading a small number of params. @ModelAttribute is used when you have a form with a large number of fields.


2 Answers

First, your POST url doen't match the controller method url, your POST url must be "/post-to-me/?param1=x&param2=y" not "/post-to-me?param1=x&param2=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

like image 102
Carlos Herrera Muñoz Avatar answered Nov 13 '22 08:11

Carlos Herrera Muñoz


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&param2=y

like image 27
okante Avatar answered Nov 13 '22 09:11

okante