Java @RequestParam对象中的枚举列表
假设我在Spring引导控制器中有一个GET端点,它接受一个对象@RequestParamJava @RequestParam对象中的枚举列表,java,spring-boot,rest,spring-mvc,enums,Java,Spring Boot,Rest,Spring Mvc,Enums,假设我在Spring引导控制器中有一个GET端点,它接受一个对象@RequestParam @GetMapping(value = "/foos") public List<Foo> getFoos(@RequestParam FilterParams filterParams) { return fooDao.getFoos(filterParams); } 如果我们在此端点上发布一个GET请求,其中包含由分隔的filterParameter属性列表,即。 curl-X GE
@GetMapping(value = "/foos")
public List<Foo> getFoos(@RequestParam FilterParams filterParams) {
return fooDao.getFoos(filterParams);
}
如果我们在此端点上发布一个GET请求,其中包含由分隔的filterParameter属性列表,即。
curl-X GET localhost:8080/foos?bar=BAZ,ZAP,Spring无法将其解析为列表,并尝试将单个值BAZ,ZAP反序列化为枚举。如果它不是枚举,它的行为也会相同,即将参数id=1,2反序列化为字符串列表的单个元素。有可能推翻这种行为吗?如果是这样,我们将如何实现这一目标
我知道我可以通过将多个参数声明为/foos?bar=BAZ&bar=ZAP来实现这一点,但这对我来说并不方便我认为查询参数不会转换为对象。处理这种情况的另一种方法是将请求参数声明为字符串。更新文档,说明请求参数支持不同的值。您可以解析此字符串并将其映射到枚举。从长远来看,当您希望支持新的值时,这种方法将有所帮助
@GetMapping(value = "/foos")
public List<Foo> getFoos(@RequestParam("bars") String filterParams) {
// Parse the String using coma as delimiter, map the String to an enum so that enum can be passed arround in the code
return fooDao.getFoos(filterParams);
}
传递以下URL现在应该可以工作了:curl-xgetlocalhost:8080/foos?bar=BAZ,ZAP
另一种方法是将查询参数声明为列表
@GetMapping(value = "/foos")
public List<Foo> getFoos(@RequestParam("bar") List<String> filterParams) {
// Parse the String using coma as delimiter, map the String to an enum so that enum can be passed arround in the code
return fooDao.getFoos(filterParams);
}
在这种情况下,URL可能会根据您的服务支持的数字a参数变长:curl-X get localhost:8080/foos?bar=BAZ&bar=ZAP试试这个-而不是@RequestParam FilterParams FilterParams use@RequestParam List bars这能回答您的问题吗?很抱歉,我没有指定它,但这只是一个狭窄的示例,我的类FilterParams将有更多attributes@Ezequiel我理解将参数封装到对象中的概念,问题在于将请求参数的多个值(由逗号分隔)解析为list@athina接受答案中的示例涵盖了param1字段,该字段是一个列表
@GetMapping(value = "/foos")
public List<Foo> getFoos(@RequestParam("bars") String filterParams) {
// Parse the String using coma as delimiter, map the String to an enum so that enum can be passed arround in the code
return fooDao.getFoos(filterParams);
}
@GetMapping(value = "/foos")
public List<Foo> getFoos(@RequestParam("bar") List<String> filterParams) {
// Parse the String using coma as delimiter, map the String to an enum so that enum can be passed arround in the code
return fooDao.getFoos(filterParams);
}