简体   繁体   English

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

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

I'd like to create a single method and configure both GET + POST on it, using spring-mvc: 我想使用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
    }
}

Problem: with the code above, any POST request leads to an empty MyReq object. 问题:使用上面的代码,任何POST请求都会导致空的MyReq对象。

If I change the method signature to @RequestBody @Valid MyReq req , then the post works, but the GET request fails. 如果我将方法签名更改为@RequestBody @Valid MyReq req ,则帖子有效,但GET请求失败。

So isn't is possible to just use get and post together on the same method, if a bean is used as input parameters? 如果bean被用作输入参数,那么就不可能在同一个方法上一起使用get和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. 您可以根据接收方式以不同方式处理请求数据,并调用相同的方法来执行业务逻辑。

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

This will work for both POST and GET. 这适用于POST和GET。 (make sure the order first POST and then GET) (确保订单先POST,然后GET)

For GET your POJO has to contain the attribute which you're using in request parameter 对于GET,您的POJO必须包含您在请求参数中使用的属性

like below 如下

public class POJO  {

private String parameter1;
private String parameter2;

   //getters and setters

URl should be like below URl应该如下所示

/test?parameter1=blah /测试?参数1 =嗒嗒

Like this way u can use it for both GET and POST 就像这样,你可以将它用于GET和POST

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

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