我已经实现了我的自定义类的列表,在此提到的验证岗位。供参考,我的代码看起来像
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");
}
}
}
}
因此,即使我发送空名称绑定结果也有0错误。我用topVar测试过,它工作正常。我的问题是是否必须做任何其他配置才能使用此验证器?
谢谢
在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
,同时还要检查白色字符(空格,制表符等)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句