繁体   English   中英

在同一方法上使用GET + POST的RestController?

[英]RestController with GET + POST on same method?

我想使用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 ,则帖子有效,但GET请求失败。

如果bean被用作输入参数,那么就不可能在同一个方法上一起使用get和post吗?

您问题的最佳解决方案似乎是这样的:

@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());
    }
}

您可以根据接收方式以不同方式处理请求数据,并调用相同的方法来执行业务逻辑。

我无法使用相同的方法工作,我想知道一个解决方案,但这是我的解决方法,与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);
    }
}
@RequestMapping(value = "/test", method = { RequestMethod.POST,  RequestMethod.GET })
public void test(@ModelAttribute("xxxx") POJO pojo) {

//your code 
}

这适用于POST和GET。 (确保订单先POST,然后GET)

对于GET,您的POJO必须包含您在请求参数中使用的属性

如下

public class POJO  {

private String parameter1;
private String parameter2;

   //getters and setters

URl应该如下所示

/测试?参数1 =嗒嗒

就像这样,你可以将它用于GET和POST

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM