Home > Enterprise >  Spring Controller to get both GET and POST variables
Spring Controller to get both GET and POST variables

Time:01-11

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.

CodePudding user response:

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

CodePudding user response:

In the request mapping you simply write this code. you can use this for both post and get mappings.

method = {RequestMethod.POST,RequestMethod.GET}

I hope you like this one.

  • Related