RestController with GET + POST on same method?

membersound :

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?

luizfzs :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=466856&siteId=1
Recommended