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

问题描述 投票:5回答:3

我想使用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吗?

java spring spring-mvc
3个回答
8
投票

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

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

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


1
投票

我无法使用相同的方法工作,我想知道一个解决方案,但这是我的解决方法,与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);
    }
}

0
投票
@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

© www.soinside.com 2019 - 2024. All rights reserved.