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?
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);
}
}
@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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With