Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestController with GET + POST on same method?

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?

like image 380
membersound Avatar asked Jun 06 '17 12:06

membersound


3 Answers

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);
    }
}
like image 116
Jason Winnebeck Avatar answered Oct 26 '22 19:10

Jason Winnebeck


@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

like image 42
MPPNBD Avatar answered Oct 26 '22 18:10

MPPNBD


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.

like image 42
luizfzs Avatar answered Oct 26 '22 18:10

luizfzs