Search code examples
javaspringrestspring-restcontrollerrequest-mapping

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


Is it possible to map same path (uri) in request mapping for two different post methods, only difference is request body.

Example

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

Solution

  • 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