关于Spring验证框架Validator的使用

在JavaEE的后端开发中,常常会涉及到数据的验证,使用Spring的验证框架可以很好的帮助我们完成需求。
在整个验证框架的使用中,主要分为了两个部分:后端验证和前端显示。
后端验证:
第一步:需要建立一个进行验证的类,并实现Validator接口

public class UserValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return User.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        User user = (User) target;
        if(null == user.getPassword() || "".equals(user.getPassword())){
            errors.rejectValue("password",null,null,"password is null");
        }
    }
}

supports方法用于判断是否是我们需要验证的类,如果不是将会抛出异常,validate方法对数据进行判断,并将判断的错误信息放在errors对象中。
第二步:在控制层(controller)中注册并使用第一步创建的验证类。(所执行的方法参数中必须包括@Validated和BindingResult,并且顺序为以前以后,处于相邻的位置,如果位置颠倒或者没有紧靠,会发生异常)

@Controller
public class UserController {

    @InitBinder
    public void initBinder(DataBinder dataBinder){
        dataBinder.replaceValidators(new UserValidator());
    }

    @RequestMapping("login.mvc")
    public String test(@Validated @ModelAttribute("user") User user, BindingResult br){
        if(br.hasErrors()){
            System.out.println("有错");
        }
        return "index";
    }
}

第三步:前端页面显示
当想要在前端页面显示错误信息的时候,提交表单必须使用表单,并为其添加modelAttribute属性(在控制层中定义的)

<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>



<sf:form action="login.mvc" method="post" modelAttribute="user">
        username:<input title="username" type="text" autocomplete="off" name="username"><br><br>
        password:<input title="password" type="password" name="password">
        <sf:errors path="password"/>
        <br>
        <input type="submit">
    </sf:form>

以上便是Spring的验证框架的验证以及显示的全过程,如有错误,请指出,谢谢

10-07 19:08