Search code examples
javaspringspring-mvccontrollerhttprequest

Spring Controller to get both GET and POST variables


Sometimes we send a POST HTTP request with POST payload to an endpoint with URL variable, for example:

[POST] http://example.com/update-item?itemid=123456

To get the POST payload in the Spring controller class, I can do something this:

@RequestMapping(value = "/update-item", method = RequestMethod.POST)
public String updateItem(@RequestBody Item json) {
    //some logics
     return "/update-item-result";
}

However, at the same time, how can I get the variable from the URL (i.e. itemid in the above example) even for method = RequestMethod.POST?

I see a lot of Spring MVC examples on the web either get the GET variables from the URL or the POST variables from the payload, but I never see getting both in action.


Solution

  • You can use multiple HTTP requests by specifying the method attribute as an array in the @RequestMapping annotation.

        @RequestMapping(value = "/update-item", method = {RequestMethod.POST,RequestMethod.GET})
    public String updateItem(@RequestBody Item json) {
        //some logics
         return "/update-item-result";
    }