Spring map将请求参数自动添加到POJO

时间:2014-10-28 15:37:13

标签: java spring spring-mvc

我的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) {
    // ......
}

我希望将所有GET请求参数映射到POJO对象,如:

public class RequestParamsModel {

   public RequestParamsModel() {

   }

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

我需要在REST控制器中使用@RequestBody来做的事情。

可以在Spring 3.x中完成吗?

谢谢!

2 个答案:

答案 0 :(得分:21)

可行且简单,确保您的bean具有适当的字段访问者。您可以为每个属性添加适当的验证,只需确保您有适当的jar。在代码方面,它将类似于

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;
    }
    //  ...
}

控制器方法是:

import javax.validation.Valid;

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

请求,例如:

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

答案 1 :(得分:2)

你想做什么

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