RestController with GET + POST on same method?

13,187

Solution 1

The best solution to your problem seems to be something like this:

@RestController
public class MyServlet {
    @RequestMapping(value = "test", method = {RequestMethod.GET})
    public void testGet(@Valid @RequestParam("foo") String foo) {
          doStuff(foo)
    }
    @RequestMapping(value = "test", method = {RequestMethod.POST})
    public void testPost(@Valid @RequestBody MyReq req) {
          doStuff(req.getFoo());
    }
}

You can process the request data in different ways depending on how you receive it and call the same method to do the business logic.

Solution 2

@RequestMapping(value = "/test", method = { RequestMethod.POST,  RequestMethod.GET })
public void test(@ModelAttribute("xxxx") POJO pojo) {

//your code 
}

This will work for both POST and GET. (make sure the order first POST and then GET)

For GET your POJO has to contain the attribute which you're using in request parameter

like below

public class POJO  {

private String parameter1;
private String parameter2;

   //getters and setters

URl should be like below

/test?parameter1=blah

Like this way u can use it for both GET and POST

Solution 3

I was unable to get this working on the same method and I'd like to know a solution, but this is my workaround, which differs from luizfzs's in that you take the same request object and not use @RequestParam

@RestController
public class Controller {
    @GetMapping("people")
    public void getPeople(MyReq req) {
        //do it...
    }
    @PostMapping("people")
    public void getPeoplePost(@RequestBody MyReq req) {
        getPeople(req);
    }
}
Share:
13,187

Related videos on Youtube

membersound
Author by

membersound

JEE + Frameworks like Spring, Hibernate, JSF, GWT, Vaadin, SOAP, REST.

Updated on September 15, 2022

Comments

  • membersound
    membersound over 1 year

    I'd like to create a single method and configure both GET + POST on it, using spring-mvc:

    @RestController
    public class MyServlet {
        @RequestMapping(value = "test", method = {RequestMethod.GET, RequestMethod.POST})
        public void test(@Valid MyReq req) {
              //MyReq contains some params
        }
    }
    

    Problem: with the code above, any POST request leads to an empty MyReq object.

    If I change the method signature to @RequestBody @Valid MyReq req, then the post works, but the GET request fails.

    So isn't is possible to just use get and post together on the same method, if a bean is used as input parameters?

    • M. Deinum
      M. Deinum almost 7 years
      If you are sending JSON that isn't really common with a GET request as that generally doesn't have a body but only parameters. Request Body != Request Parameters. So you either use binding or serialization not both.