由于springmvc 3.x现在支持jsr303和旧的spring style验证器,我想在我的示例应用程序中混合它们.但是只有一个方法为指定的控制器启用,是弹簧框架或JSR标准的限制吗?
这是我的示例代码.
User.java代表域模型,使用JSR303进行验证.
public class User{
@Size(max = 16,message = "user loginId max-length is 16")
private String loginId;
//omit getter and setter
}
UserValidator.java,实现org.springframework.validation.Validator接口以支持用户验证.
public class UserValidator implements Validator {
private UserService userService;
public boolean supports(Class> clazz) {
return User.class.isAssignableFrom(clazz);
}
public void validate(Object target,Errors errors) {
User u = (User) target;
// loginName check for new user
if (u.getUserId() == null && !userService.isLoginIdUnique(u.getLoginId(),null)) {
errors.rejectValue("loginId","user.loginId.unique",new Object[] { u.getLoginId() },null);
}
}
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
}
UserController.java,使用InitBinder注释将UserValidator注入WebDataBinder.
@Controller("jspUserController")
@RequestMapping("/sys/users")
public class UserController {
private UserValidator userValidator;
@Autowired
public void setUserValidator(UserValidator userValidator) {
this.userValidator = userValidator;
}
/*@InitBinder("user")
public void initBinderUser(WebDataBinder binder) {
binder.setValidator(userValidator);
}*/
@RequestMapping(value = "/save")
public String save(@Valid User user,BindingResult bindingResult,Model model,HttpServletRequest request) {
if (bindingResult.hasErrors()) {
return "/sys/user/edit";
}
userService.saveUser(user);
return "redirect:/sys/users/index";
}
}
如果我取消注释UserController中的@InitBinder(“user”),将禁用JSR303验证.虽然当前注释的代码将使用JSR验证器来进行验证.
任何人都可以给我一个解决方法,将它们混合在一个控制器中?
最佳答案
您可以直接使用验证器,并让全局LocalValidatorfactorybean(JSR-303)也能正常工作:
原文链接:https://www.f2er.com/springmvc/431850.html @Controller("jspUserController")
@RequestMapping("/sys/users")
public class UserController {
private UserValidator userValidator;
@Autowired
public void setUserValidator(UserValidator userValidator) {
this.userValidator = userValidator;
}
@RequestMapping(value = "/save")
public String save(@Valid User user,HttpServletRequest request) {
this.userValidator.validate(user,bindingResult);
if (bindingResult.hasErrors()) {
return "/sys/user/edit";
}
userService.saveUser(user);
return "redirect:/sys/users/index";
}
}