我已经实现了对自定义类列表的验证,如 post 中所述.作为引用,我的代码看起来像
class TopDtoForm {
@NotEmpty
private String topVar;
private List<DownDto> downVarList;
//getter and setter
}
class DownDto {
private Long id;
private String name;
//getter and setter
}
@Component
public class TopDtoFormValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return TopDtoForm.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
TopDtoForm topDtoForm = (TopDtoForm) target;
for(int index=0; index<topDtoForm.getDownVarList().size(); index++) {
DownDto downDto = topDtoForm.getDownVarList().get(index);
if(downDto.getName().isEmpty()) {
errors.rejectValue("downVarList[" + index + "].name", "name.empty");
}
}
}
}
所以即使我发送空名称绑定(bind)结果也有 0 个错误。我用 topVar 测试过,它工作正常。我的问题是我是否必须进行任何其他配置才能使用此 validator ?
谢谢
最佳答案
在 Spring MVC 中,只需在 TopDtoForm 中使用 @Valid
注释您的列表并将 @NotEmpty
添加到 DownDto
。 Spring 会很好地验证它:
class TopDtoForm {
@NotEmpty
private String topVar;
@Valid
private List<DownDto> downVarList;
//getter and setter
}
class DownDto {
private Long id;
@NotEmpty
private String name;
//getter and setter
}
然后在 RequestMapping 中:
@RequestMapping(value = "/submitForm.htm", method = RequestMethod.POST) public @ResponseBody String saveForm(@Valid @ModelAttribute("topDtoForm") TopDtoForm topDtoForm, BindingResult result) {}
还可以考虑从 @NotEmpty
切换到 @NotBlank
,同时检查白色字符(空格、制表符等)
关于java - 嵌套类列表的 Spring 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25872109/