Spring - 是否可以在请求映射中为两种不同的 post 方法提供相同的 url (路径)?

Spring - is it possible to give same url (path) in request mapping for two different post methods?

是否可以在请求映射中为两种不同的post方法映射相同的路径(uri),唯一的区别是请求正文。

例子

  @RequestMapping(value = "/hello", method = RequestMethod.POST)
  public String helloEmployee(@RequestBody Employee employee) {
    return "Hello Employee";
  }

  @RequestMapping(value = "/hello", method = RequestMethod.POST)
  public String helloStudent(@RequestBody Student student) {
    return "Hello Student";
  }

是的,你可以这样做,但你需要在 RequestMapping 注释中指定唯一的参数签名:

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
}

}

`

不,您不能在具有不同请求正文类型但相同媒体类型的 post 方法的请求映射中提供相同的 url。以下将不起作用:

  @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";
  }

如果您有不同的媒体类型,那么它会。以下将起作用:

  @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";
  }

您的 RequestMapping 应该至少在一个条件上有所不同; path,method,params,headers,consumes,produces

我需要相同的 url post 映射,但它给我一个错误,所以我添加了不同的参数,它对我有用

//url1 post mapping
@PostMapping(value = {"/applicant/{step}" ,params = "validatedata")

//url2 post mapping
@PostMapping(value = {"/applicant/{step}" ,params = "data")

如果以下任何一项不同(如上述答案所述),那么您可以拥有相同的 URL post 映射 路径、方法、参数、headers、消费、生产

在我的例子中参数是不同的