Spring - is possible to give same url in request mapping of post method?

柔情痞子 提交于 2019-12-25 18:31:30

问题


Is that possible to use same url in request mapping for two different post method, only request body differs.


回答1:


No, you can't give same url in request mapping of post method having different request body type but same media type. Below won't work:

  @PostMapping(path = "/hello", consumes = MediaType.APPLICATION_JSON_VALUE)
  public String hello(@RequestBody Pojo1 val) {
    return "Hello";
  }

  @PostMapping(path = "/hello", consumes = MediaType.APPLICATION_JSON_VALUE)
  public String hello(@RequestBody Pojo2 val) {
    return "Hello";
  }

If you have different media type, then it will. Below will work:

  @PostMapping(path = "/hello", consumes = MediaType.APPLICATION_JSON_VALUE)
  public String hello(@RequestBody Pojo val) {
    return "Hello";
  }

  @PostMapping(path = "/hello", consumes = MediaType.TEXT_PLAIN_VALUE)
  public String hello(@RequestBody String val) {
    return "Hello";
  }

Your RequestMapping should differ on at least one of the conditions; path,method,params,headers,consumes,produces




回答2:


Yes you can do that but you need to specify unique parameters signature in RequestMapping annotation:

public class MyController {

@RequestMapping(method = RequestMethod.POST, params = {"!name", "!name2"})
public String action(HttpServletRequest request, HttpServletResponse response){
    // body
}

@RequestMapping(method = RequestMethod.POST, params = "name")
public String action(HttpServletRequest request, HttpServletResponse response,
                        @RequestParam(value = "name", required = true) String name) {
    // body
}

}

`



来源:https://stackoverflow.com/questions/53519006/spring-is-possible-to-give-same-url-in-request-mapping-of-post-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!