gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:52:40 24 4
gpt4 key购买 nike

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

@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 所做的那样。

可以在 Spring 3.x 中做吗?

谢谢!

最佳答案

可能且简单,请确保您的 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;
}
// ...
}

Controller 方法是:

import javax.validation.Valid;

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

还有请求,比如:

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

关于java - Spring自动将GET请求参数映射到POJO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26612404/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com