Java Spring 将 GET 请求参数自动映射到 POJO

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26612404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:55:51  来源:igfitidea点击:

Spring map GET request parameters to POJO automatically

javaspringspring-mvc

提问by IgorOK

I have method in my REST controller that contains a lot of parameters. For example:

我的 REST 控制器中有包含很多参数的方法。例如:

@RequestMapping(value = "/getItem", method = RequestMethod.GET)
public ServiceRequest<List<SomeModel>> getClaimStatuses(
        @RequestParam(value = "param1", required = true) List<String> param1,
        @RequestParam(value = "param2", required = false) String param2,
        @RequestParam(value = "param3", required = false) List<String> param3,
        @RequestParam(value = "param4", required = false) List<String> param4,
        @RequestParam(value = "param5", required = false) List<String> param5) {
    // ......
}

and I would like to map all GET request parameters to a POJO object like:

我想将所有 GET 请求参数映射到一个 POJO 对象,例如:

public class RequestParamsModel {

   public RequestParamsModel() {

   }

   public List<String> param1;
   public String param2;
   public List<String> param3;
   public String param4;
   public String param5;
}

I need something like we can do using @RequestBody in REST Controller.

我需要一些我们可以在 REST 控制器中使用 @RequestBody 的东西。

Is it possible to do in Spring 3.x ?

可以在 Spring 3.x 中做吗?

Thanks!

谢谢!

采纳答案by Master Slave

Possible and easy, make sure that your bean has proper accessors for the fields. You can add proper validation per property, just make sure that you have the proper jars in place. In terms of code it would be something like

可能且简单,确保您的 bean 具有适当的字段访问器。您可以为每个属性添加适当的验证,只需确保您有适当的 jars。就代码而言,它类似于

import javax.validation.constraints.NotNull;

public class RequestParamsModel {

    public RequestParamsModel() {}

    private List<String> param1;
    private String param2;
    private List<String> param3;
    private String param4;
    private String param5;

    @NotNull
    public List<String> getParam1() {
        return param1;
    }
    //  ...
}

The controller method would be:

控制器方法是:

import javax.validation.Valid;

@RequestMapping(value = "/getItem", method = RequestMethod.GET)
public ServiceRequest<List<SomeModel>> getClaimStatuses(@Valid RequestParamsModel model) {
    // ...
}

And the request, something like:

和请求,类似于:

/getItem?param1=list1,list2&param2=ok

回答by Serge Ballesta

Are you trying to do

你想做什么

@RequestMapping(value = "/getItem", method = RequestMethod.GET)
public ServiceRequest<List<SomeModel>> getClaimStatuses(@ModelAttribute RequestParamsModel requestParamModel) {
...
}