验证Spring中的对象列表 [英] Validation of a list of objects in Spring
问题描述
我有以下控制器方法:
@RequestMapping(value="/map/update", method=RequestMethod.POST, produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseEntityWrapper updateMapTheme(
HttpServletRequest request,
@RequestBody @Valid List<CompanyTag> categories,
HttpServletResponse response
) throws ResourceNotFoundException, AuthorizationException {
...
}
CompanyTag的定义方式如下:
CompanyTag is defined this way:
public class CompanyTag {
@StringUUIDValidation String key;
String value;
String color;
String icon;
Icon iconObj;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
...
}
问题在于未触发验证,未验证CompanyTag列表,从不调用StringUUIDValidation验证程序。
The problem is that validation is not triggered, the CompanyTag list is not validated, the "StringUUIDValidation" validator is never called.
如果我删除了List并且只尝试发送一个CompanyTag,即代替:
If I remove the List and only try to send a single CompanyTag, i.e. instead of:
@RequestBody @Valid List<CompanyTag> categories,
使用:
@RequestBody @Valid CompanyTag category,
它按预期工作,显然Spring不喜欢验证事物列表(尝试使用数组,但也没有用)。
it works as expected, so apparently Spring does not like to validate lists of things (tried with array instead, that did not work either).
任何人都知道缺少什么?
Anybody have any idea what's missing?
推荐答案
我发现了另一个有效的方法。基本问题是您希望将列表作为服务的输入有效负载,但javax.validation不会验证列表,只验证JavaBean。诀窍是使用一个自定义列表类,它既可以作为List 又可以作为一个JavaBean:
I found another approach that works. The basic problem is that you want to have a list as your input payload for your service, but javax.validation won't validate a list, only a JavaBean. The trick is to use a custom list class that functions as both a List and a JavaBean:
@RequestBody @Valid List<CompanyTag> categories
更改为:
@RequestBody @Valid ValidList<CompanyTag> categories
您的列表子类看起来像这样:
Your list subclass would look something like this:
public class ValidList<E> implements List<E> {
@Valid
private List<E> list;
public ValidList() {
this.list = new ArrayList<E>();
}
public ValidList(List<E> list) {
this.list = list;
}
// Bean-like methods, used by javax.validation but ignored by JSON parsing
public List<E> getList() {
return list;
}
public void setList(List<E> list) {
this.list = list;
}
// List-like methods, used by JSON parsing but ignored by javax.validation
@Override
public int size() {
return list.size();
}
@Override
public boolean isEmpty() {
return list.isEmpty();
}
// Other list methods ...
}
这篇关于验证Spring中的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!