在spring mvc3中同时使用@RequestBody和@RequestParam

Aja*_*jay 7 spring spring-mvc

我使用spring-mvc 3.1.0.RELEASE,由于某种原因,使用查询参数和请求正文映射POST不起作用.

以下是我的控制器方法的外观:

  @RequestMapping(method = POST, value = "/post-to-me/") 
  public void handlePost(
    @RequestBody Content content,
    @RequestParam("param1") String param1,
    @RequestParam("param2") String param2
  ){
       //do stuff       
  }
Run Code Online (Sandbox Code Playgroud)

但是,如果我将所有请求参数转换为路径参数,则映射有效.有没有人碰到类似的东西?

谢谢!

编辑:"不起作用"== 404我尝试的时候, POST /post-to-me?param1=x&param2=y

小智 1

首先,您的 POST url 与控制器方法 url 不匹配,您的 POST url 必须是“/post-to-me/?param1=x¶m2=y”而不是“/post-to-me?param1=x¶m2=y”

二、Content类从何而来?我使用了一个字符串并且对我来说效果很好

@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);
}
Run Code Online (Sandbox Code Playgroud)

请注意,我使用 HttpServletResponse 返回 HTTP 200 代码,但我认为返回 Http 代码有更好的解决方案,请检查:Multiple response http status in Spring MVC