简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM