我想创建一个方法,并使用spring-mvc在其上配置GET + POST:
@RestController
public class MyServlet {
@RequestMapping(value = "test", method = {RequestMethod.GET, RequestMethod.POST})
public void test(@Valid MyReq req) {
//MyReq contains some params
}
}
问题:使用上面的代码,任何POST
请求都会导致一个空的MyReq
对象。
如果我将方法签名更改为@RequestBody @Valid MyReq req
,则post可以工作,但GET
请求失败。
那么,如果将bean用作输入参数,那么在同一个方法上同时使用get和post是不可能的吗?
发布于 2017-06-06 20:09:49
对你的问题最好的解决方案似乎是这样的:
@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());
}
}
您可以根据接收数据的方式以不同的方式处理请求数据,并调用相同的方法来执行业务逻辑。
发布于 2017-09-12 21:53:17
@RequestMapping(value = "/test", method = { RequestMethod.POST, RequestMethod.GET })
public void test(@ModelAttribute("xxxx") POJO pojo) {
//your code
}
这对POST和GET都有效。(请确保订单先发布,然后获取)
对于GET,您的POJO必须包含您在请求参数中使用的属性
如下所示
public class POJO {
private String parameter1;
private String parameter2;
//getters and setters
URl应该如下所示
/test?parameter1=blah
就像这样,你可以将它用于GET和POST
发布于 2018-06-16 02:38:17
我不能让它在相同的方法上工作,我想知道一个解决方案,但这是我的变通方法,它与luizfzs的不同之处在于,您可以接受相同的请求对象,而不使用@RequestParam
@RestController
public class Controller {
@GetMapping("people")
public void getPeople(MyReq req) {
//do it...
}
@PostMapping("people")
public void getPeoplePost(@RequestBody MyReq req) {
getPeople(req);
}
}
https://stackoverflow.com/questions/44389498
复制相似问题