@Controller
public class MyController {
@RequestMapping(value="/result")
public String registerForm(Model model){
User user = new User();
model.addAttribute("user", user);
return "result";
}
@InitBinder
public void initBinder(DataBinder binder){
binder.setValidator(new UserValidator());
}
@RequestMapping(value="/click")
public String register(@Validated User user,Errors errors){
if(errors.hasFieldErrors())return "result";
return "success";
}
}
public class UserValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return User.class.equals(clazz);
}
@Override
public void validate(Object object, Errors errors) {// 验证
ValidationUtils.rejectIfEmpty(errors, "username", null, "用户名不能为空");
ValidationUtils.rejectIfEmpty(errors, "sex", null, "性别不能为空");
ValidationUtils.rejectIfEmpty(errors, "age", null, "年龄不能为空");
}
}