zoukankan      html  css  js  c++  java
  • SpringMVC——数据校验

    数据校验在web应用里是非常重要的功能,尤其是在表单输入中。在这里采用Hibernate-Validator进行校验,该方法实现了JSR-303验证框架支持注解风格的验证。

    一、导入jar包

    若要实现数据校验功能,需要导入必要的jar包,主要包括以下几个:

    • classmate-1.3.1.jar
    • hibernate-validator-5.4.1.Final.jar
    • hibernate-validator-annotation-processor-5.4.1.Final.jar
    • hibernate-validator-cdi-5.4.1.Final.jar
    • jboss-logging-3.3.0.Final.jar
    • validation-api-1.1.0.Final.jar

    二、常用的校验注解

    注解功能
    @Null 验证对象是否为 null
    @NotNull 验证对象是否不为 null
    @AssertTrue 验证 Boolean 对象是否为 true
    @AssertTrue 验证 Boolean 对象是否为 false
    @Max(value) 验证 Number 和 String 对象是否小于等于指定值
    @Min(value) 验证 Number 和 String 对象是否大于等于指定值
    @DecimalMax(value) 验证注解的元素值小于等于 @DecimalMax 指定的 value 值
    @DecimalMin(value) 验证注解的元素值大于等于 @DecimalMin 指定的 value 值
    @Digits(integer,fraction) 验证字符串是否符合指定格式的数字,integer 指定整数精度,fraction 指定小数精度
    @Size(min,max) 验证对象长度是否在给定的范围内
    @Past 验证 Date 和 Calendar 对象是否在当前时间之前
    @Future 验证 Date 和 Calendar 对象是否在当前时间之后
    @Pattern 验证 String 对象是否符合正则表达式的规则
    @NotBlank 检查字符串是不是 Null,被 Trim 的长度是否大于0,只对字符串,且会去掉前后空格
    @URL 验证是否是合法的 url
    @Email 验证是否是合法的邮箱
    @CreditCardNumber 验证是否是合法的信用卡号
    @Length(min,max) 验证字符串的长度必须在指定范围内
    @NotEmpty 检查元素是否为 Null 或 Empty
    @Range(min,max,message) 验证属性值必须在合适的范围内

    三、修改实体类

    在类的属性上进行标注,如:

    public class User {
        @NotBlank(message = "Username can not be empty")
        private String username;
        @NotBlank(message = "password can not be blank")
        @Length(min = 6, max = 16, message = "The length of the password must be between 6 and 16 bits")
        private String password;
        @Range(min = 18, max = 60, message = "Age must be between 18 and 60 years old")
        private Integer age;
        @Pattern(regexp = "^1[3|4|5|7|8][0-9]{9}$", message = "Please enter the correct format of the phone number")
        private String phone;
        @Email(message = "Please enter a valid email address")
        private String email;
    
        // other...   
    }

    四、修改相应的处理方法

    @RequestMapping(value = "/register")
    public String register(@Valid  @ModelAttribute("user") User user, Errors errors,Model model) {
        if(errors.hasErrors()){
            return "register";
        }
        model.addAttribute("user", user);
        return "success";
    }

    五、视图输出

    校验之后,我们通常需要在表单的输入框后进行文字反馈:

    <form:form modelAttribute="user" method="post" action="register">
        <fieldset>
            <legend>register</legend>
            <p>
                <label>name:</label>
                <form:input path="username" />
                <form:errors path="username" cssStyle="color:red"/>
            </p>
             ...
        </fieldset>
    </form:form>

    然而,有些时候并不推荐直接将错误信息写在注解的message属性里,这样不方便国际化。因此可以做以下几处修改:

    1. 新建validatemessages.properties

    username.not.blank = "username cannot be empty..."
    password.not.blank = "password cannot be empty"
    password.not.length = "password should be in 6-10"
    age.not.range = "age should be in 10-70"
    phone.not.pattern = "phone should be in format"
    email.not.format = "email should be in format"

    2. 实体类中的注解使用相对引用

    public class User {
        
        @NotBlank(message = "{username.not.blank}")
        private String username;
        
        @NotBlank(message = "{password.not.blank}")
        @Length(min = 6, max = 10, message = "{password.not.length}")
        private String password;
        
        @Range(min = 10, max = 70, message = "{age.not.range}")
        private Integer age;
        
        @Pattern(regexp = "^1[3|4|5|7|8][0-9]{9}$", message = "{phone.not.pattern}")
        private String phone;
        
        @Email(message = "{email.not.format}")
        private String email;
        
    //
    other... }

    3. 修改配置文件

        <!-- 默认的注解映射的支持 -->  
        <mvc:annotation-driven validator="validator" conversion-service="conversion-service" />
        
        <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
            <property name="providerClass"  value="org.hibernate.validator.HibernateValidator"/>
            <!--不设置则默认为classpath下的 ValidationMessages.properties -->
            <property name="validationMessageSource" ref="validatemessageSource"/>
        </bean>
        <bean id="conversion-service" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />
        <bean id="validatemessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">  
            <property name="basename" value="classpath:validatemessages"/>  
            <property name="fileEncodings" value="utf-8"/>  
            <property name="cacheSeconds" value="120"/>  
        </bean>

    特别注意:value="classpath:validatemessages",文件名不加后缀!

    至此,数据校验的整个过程就结束了。

    最后还要特别强调的重点是:

    • 视图中<form:form modelAttribute="contentModel" method="post">的modelAttribute="xxx"后面的名称xxx必须与对应的@Valid @ModelAttribute("xxx") 中的xxx名称一致,否则模型数据和错误信息都绑定不到。
    • <form:errors path="name"></form:errors>即会显示模型对应属性的错误信息,当path="*"时则显示模型全部属性的错误信息。

    参考地址:

    http://www.cnblogs.com/liukemng/p/3738055.html

  • 相关阅读:
    代码:城市名称的联想下拉框。可按拼音搜索、按汉字搜索,是一种很简单的实现方式
    代码:拖拽
    插件:zTree
    代码:遍历
    学习笔记:Stage.js(又叫Cut.js)——2D canvas 开发库,游戏方面的
    前端模块化、构建工具
    二级联动下拉菜单
    thinkphp的目录结构设计经验总结
    tp 路径表示
    liunx 根目录介绍
  • 原文地址:https://www.cnblogs.com/thErving/p/6926264.html
Copyright © 2011-2022 走看看