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

后端 未结 3 1587
情歌与酒
情歌与酒 2021-01-21 18:12

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

相关标签:
3条回答
  • 2021-01-21 18:37

    I needed the same url post mapping but it was giving me an error so I added different params and it worked for me

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

    if any of the below is different(as mentioned by the above answers)then you can have the same URL post mapping path,method,params,headers,consumes,produces

    In my case params was diffrent

    0 讨论(0)
  • 2021-01-21 18:42

    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

    0 讨论(0)
  • 2021-01-21 18:50

    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
    }
    
    }
    

    `

    0 讨论(0)
提交回复
热议问题