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

我的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 Controller中使用@RequestBody一样的方法。

谢谢!

回答:

可能且容易,请确保您的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

以上是 将GET请求参数自动映射到POJO 的全部内容, 来源链接: utcz.com/qa/426244.html

回到顶部