zoukankan      html  css  js  c++  java
  • 吴裕雄天生自然Spring BootSpring Boot与Thymeleaf的表单验证

    使用Hibernate Validator验证表单时,需要利用它的标注类型在实体模型的属性上嵌入约束。
    空检查
    
    @Null:验证对象是否为null。
    @NotNull:验证对象是否不为null,无法查检长度为0的字符串。
    @NotBlank:检查约束字符串是不是null,还有被trim后的长度是否大于0,只对字符
    串,且会去掉前后空格。
    @NotEmpty:检查约束元素是否为null或者是empty。
    示例如下:
    @NotBlank(message="{goods.gname.required}")//goods.gname.required为属性文件的错误代码
    private String gname;
    booelan检查
    
    @AssertTrue:验证boolean属性是否为true。
    @AssertFalse:验证boolean属性是否为false。
    示例如下:
    @AssertTrue
    private boolean isLogin;
    长度检查
    
    @Size(min=, max=):验证对象(Array,Collection,Map,String)长度是否在给定的范围之内。
    @Length(min=, max=):验证字符串长度是否在给定的范围之内。
    示例如下:
    @Length(min=1,max=100)
    private String gdescription;
    日期检查
    
    @Past:验证Date和Calendar对象是否在当前时间之前。
    @Future:验证Date和Calendar对象是否在当前时间之后。
    @Pattern:验证String对象是否符合正则表达式的规则。
    示例如下:
    @Past(message="{gdate.invalid}")
    private Date gdate;
    数值检查
    
    @Min:验证Number和String对象是否大等于指定的值。
    @Max:验证Number和String对象是否小等于指定的值。
    @DecimalMax:被标注的值必须不大于约束中指定的最大值,这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示,小数存在精度。
    @DecimalMin:被标注的值必须不小于约束中指定的最小值,这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示,小数存在精度。
    @Digits:验证Number和String的构成是否合法。
    @Digits(integer=,fraction=):验证字符串是否符合指定格式的数字,interger指定整数精度,fraction指定小数精度。
    @Range(min=, max=):检查数字是否介于min和max之间。
    @Valid:对关联对象进行校验,如果关联对象是个集合或者数组,那么对其中的元素进行校验,如果是一个map,则对其中的值部分进行校验。
    @CreditCardNumber:信用卡验证。
    @Email:验证是否是邮件地址,如果为null,不进行验证,通过验证。
    示例如下:
    @Range(min=0,max=100,message="{gprice.invalid}")
    private double gprice;
    使用Hibernate Validator验证表单的过程
    
    1.创建表单实体模型
    
    2.创建控制器
    
    3.创建视图页面
    
    4.运行
    应用的com.ch.ch5_1.model包中,创建表单实体模型类Goods。在该类使用Hibernate Validator的标注类型进行表单验证
    
    public class Goods {
        @NotBlank(message="商品名必须输入")
        @Length(min=1, max=5, message="商品名长度在1到5之间")
        private String gname;
        @Range(min=0,max=100,message="商品价格在0到100之间")
        private double gprice;
        //省略set和get方法
    }
    创建控制器
    
    应用的com.ch.ch5_1.controller包中,创建控制器类TestValidatorController。在该类中有两个处理方法,一个是界面初始化处理方法testValidator,一个是添加请求处理方法add。在add方法中,使用@Validated注解使验证生效。
    
    @RequestMapping(value="/add")
        public String add(@ModelAttribute("goodsInfo") @Validated Goods goods,BindingResult rs){
            //@ModelAttribute("goodsInfo")与th:object="${goodsInfo}"相对应
            if(rs.hasErrors()){//验证失败
                   return "testValidator";
               }
            //验证成功,可以到任意地方,在这里直接到testValidator界面
            return "testValidator";
        }
    创建视图页面
    
    应用的src/main/resources/templates目录下,创建视图页面testValidator.html。在视图页面中,直接读取到ModelAttribute里面注入的数据,然后通过th:errors="*{xxx}"获得验证错误信息。
    <project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.goods</groupId>
        <artifactId>SpringBootGoods</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.0.RELEASE</version>
            <relativePath /> <!-- lookup parent from repository -->
        </parent>
    
        <properties>
            <!-- 声明项目配置依赖编码格式为 utf-8 -->
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <fastjson.version>1.2.24</fastjson.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>
    server.servlet.context-path=/ch5_1
    spring.messages.basename=i18n/admin/adminMessages,i18n/before/beforeMessages,i18n/common/commonMessages
    package com.ch.ch5_1.model;
    
    import javax.validation.constraints.NotBlank;
    import org.hibernate.validator.constraints.Length;
    import org.hibernate.validator.constraints.Range;
    
    public class Goods {
        @NotBlank(message = "商品名必须输入")
        @Length(min = 1, max = 5, message = "商品名长度在1到5之间")
        private String gname;
        @Range(min = 0, max = 100, message = "商品价格在0到100之间")
        private double gprice;
    
        public String getGname() {
            return gname;
        }
    
        public void setGname(String gname) {
            this.gname = gname;
        }
    
        public double getGprice() {
            return gprice;
        }
    
        public void setGprice(double gprice) {
            this.gprice = gprice;
        }
    }
    package com.ch.ch5_1.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.validation.BindingResult;
    import org.springframework.validation.annotation.Validated;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    import com.ch.ch5_1.model.Goods;
    
    @Controller
    public class TestValidatorController {
        @RequestMapping("/testValidator")
        public String testValidator(@ModelAttribute("goodsInfo") Goods goods) {
            goods.setGname("商品名初始化");
            goods.setGprice(0.0);
            return "testValidator";
        }
    
        @RequestMapping(value = "/add")
        public String add(@ModelAttribute("goodsInfo") @Validated Goods goods, BindingResult rs) {
            // @ModelAttribute("goodsInfo")与th:object="${goodsInfo}"相对应
            if (rs.hasErrors()) {// 验证失败
                return "testValidator";
            }
            // 验证成功,可以到任意地方,在这里直接到testValidator界面
            return "testValidator";
        }
    }
    package com.ch.ch5_1;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class Ch51Application {
        public static void main(String[] args) {
            SpringApplication.run(Ch51Application.class, args);
        }
    }
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
        <h2>通过th:object访问对象的方式</h2>
        <div th:object="${goodsInfo}">
            <p th:text="*{gname}"></p>
            <p th:text="*{gprice}"></p>
        </div>
        <h1>表单提交</h1>
        <!-- 表单提交用户信息,注意表单参数的设置,直接是*{} -->
         <form  th:action="@{/add}" th:object="${goodsInfo}" method="post">  
          <div><span>商品名</span><input type="text" th:field="*{gname}"/><span th:errors="*{gname}"></span></div>
          <div><span>商品价格</span><input type="text" th:field="*{gprice}"/><span th:errors="*{gprice}"></span></div>
          <input type="submit" />  
        </form> 
    </body>
    </html>

     

     

  • 相关阅读:
    ThingJS之二十六问
    物联网开发,thingjs让您事半功倍!
    thingjs在线开发平台介绍
    jQuery· CSS样式方法
    jQuery属性
    jQuery效果
    JS事件委托中同一个标签执行不同操作
    js+php+mysql实现的学生成绩管理系统
    函数防抖
    两数之和
  • 原文地址:https://www.cnblogs.com/tszr/p/15315106.html
Copyright © 2011-2022 走看看