springMVC validator验证的使用

http://blog.csdn.net/miketom155/article/details/45058195

 1. 实现Validator接口,对数据进行校验 

  

@RequestMapping(value = "/pets/new", method = RequestMethod.POST)
public String processCreationForm(Owner owner, @Valid Pet pet, BindingResult result, ModelMap model) {
if (StringUtils.hasLength(pet.getName()) && pet.isNew() && owner.getPet(pet.getName(), true) != null){
result.rejectValue("name", "duplicate", "already exists");
}
if (result.hasErrors()) {
model.put("pet", pet);
return VIEWS_PETS_CREATE_OR_UPDATE_FORM;
} else {
owner.addPet(pet);
this.clinicService.savePet(pet);
return "redirect:/owners/{ownerId}";
}
}

@InitBinder("pet")
public void initPetBinder(WebDataBinder dataBinder) {
dataBinder.setValidator(new PetValidator());
}

@InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
}

2. 通过注解方式对数据进行校验

@Column(name = "address")
@NotEmpty
private String address;

@RequestMapping(value = "/owners/{ownerId}/edit", method = RequestMethod.POST)
public String processUpdateOwnerForm(@Valid Owner owner, BindingResult result, @PathVariable("ownerId") int ownerId) {
if (result.hasErrors()) {
return VIEWS_OWNER_CREATE_OR_UPDATE_FORM;
} else {
owner.setId(ownerId);
this.clinicService.saveOwner(owner);
return "redirect:/owners/{ownerId}";
}
}

原文地址:https://www.cnblogs.com/newlangwen/p/6626950.html