Can I use @Requestparam annotation for a Post request?

前端 未结 5 855
名媛妹妹
名媛妹妹 2020-12-02 19:10

I have this controller method:

@PostMapping(
        value = \"/createleave\",
        params = {\"start\",\"end\",\"hours\",\"username\"})
public void creat         


        
5条回答
  •  臣服心动
    2020-12-02 19:33

    What you are asking for is fundamentally wrong. POST requests sends data in a body payload, which is mapped via @RequestBody. @RequestParam is used to map data through the URL parameters such as /url?start=foo. What you are trying to do is use @RequestParam to do the job of @RequestBody.

    Alternative solutions for REST controllers

    • Introduce a DTO class. It is the most preferred and clean method.
    • If you really want to avoid creating a class, you can use @RequestBody Map payload. Be sure to include 'Content-Type': 'application/json' in your request header.
    • If you really want to use @RequestParam, use a GET request instead and send your data via URL parameters.

    Alternative solutions for MVC controllers

    • Introduce a DTO class and use it with annotation @ModelAttribute.
    • If you transform the form data into JSON, you can use @RequestBody Map payload. To do this, please see this answer.

    It is not possible to map form data encoded data directly to a Map.

提交回复
热议问题