springmvc jsr303验证器在一个动作中与spring WebDataBinder验证器共存

前端之家收集整理的这篇文章主要介绍了springmvc jsr303验证器在一个动作中与spring WebDataBinder验证器共存前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

由于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

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)也能正常工作:

    @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";
        }
    }
原文链接:https://www.f2er.com/springmvc/431850.html

猜你在找的SpringMVC相关文章