美文网首页
SpringBoot对表单做数据校验

SpringBoot对表单做数据校验

作者: 09c72470861c | 来源:发表于2019-01-15 18:11 被阅读0次

    1. SpringBoot对表单数据校验的技术特点

    1.1 SpringBoot中使用了Hibernate-validate校验框架

    在web启动器中引用了hibernate-validator-6.0.12.Final.jar

    引用jar

    2. SpringBoot表单数据校验步骤

    • 实体类属性上加上校验注解
    package top.mau5.pojo;
    
    import org.hibernate.validator.constraints.NotBlank;
    
    public class User {
        @NotBlank(message="用户名不能为空")
        private String name; 
        @NotBlank(message="密码不能为空")
        private String password;
        @NotBlank
        private Integer age;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        public User(String name, String password, Integer age) {
            super();
            this.name = name;
            this.password = password;
            this.age = age;
        }
        public User() {
            super();
        }
        @Override
        public String toString() {
            return "User [name=" + name + ", password=" + password + ", age=" + age + "]";
        }   
    }
    
    • Controller方法上传参处加上@Valid注解
    package top.mau5.controller;
    
    import javax.validation.Valid;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import top.mau5.pojo.User;
    
    /**
     * SpringBoot表单数据校验
     * @author korin
     * UserController.java
     * 3:35:36 PM
     */
    @Controller
    public class UserController {
    
        /**
         * 页面显示异常的方式,可以在跳转页面的方法中注入一个User对象,
         * 注意,由于springmvc会将该对象放入到model中传递,
         * key的名称会使用该对象的驼峰命名规则来作为key,
         * 参数的变量名需要与对象的名称相同,将首字母小写
         * 
         * 如果想改个名称,用注解ModelAttribute("name")来标明,
         * 这个参数在model中的key为"name"
         * @param user
         * @return
         */
        @RequestMapping("/addUser")
        public String showPage(@ModelAttribute("u") User uuuu) {
            return "add";
        }
        
        /**
         * valid注解:开启校验 
         * @param user
         * @param result
         * @return
         */
        @RequestMapping("/save")
        public String save(@Valid @ModelAttribute("u")User user,BindingResult result) {
            if(result.hasErrors()) {
                return "add";
            }
            return "ok";
        }
        
    }
    

    注意:在Controller的方法的参数中,通常User的对象参数名和类一样,在这里可以随意取,如:uuuu,因为在spring中,默认使用类名的小驼峰命名法来表示该类对象,如:User的对象名为user,而该类属性的验证信息是自动放入了Model的对象中传到了页面中,键名为“user.属性名”;而这个键名也是可以修改的,在我的Controller中,使用了@ModelAttribute("u")来注解,表示返回给页面的关于User的验证信息的键名都改为了“u.属性名”。

    • 页面中用th:errors="${}"来显示不满足要求的数据的信息
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    
        <form th:action="@{/save}" method="post">
            用户姓名:<input type="text" name="name"/><font color="red" th:errors="${u.name}"></font><br/>
            用户密码:<input type="password" name="password"/><font color="red" th:errors="${u.password}"></font><br/>
            用户年龄:<input type="text" name="age"/><font color="red" th:errors="${u.age}"></font><br/>
            <input type="submit" value="OK"/>       
        </form>
    
    </body>
    </html>
    
    • 测试
      测试

    常用校验注解

    注解 解释 示例
    @NotNull 判断任何类型的数据是否为空 @NotNull(message="不能为空")
    @NotBlank 判断字符串是否为null或者是空串(去掉首尾空格) @NotBlank(message="不能为空")
    @NotEmpty 判断字符串是否null或者是空串 @NotEmpty(mesage="不能为空")
    @Length 判断字符的长度(最大或者最小) @Length(min=2,max=6,message="最大2,最小6")
    @Min 判断数值最小值 @Min(value=15,message="信息")
    @Max 判断数值最大值 @Max(value=15,message="信息")
    @Email 判断邮箱格式是否合法 @Email或@Email(regexp="正则表达式")
    @Past 判断时间是否是过去的 @Past(message = "生日必须是过去")
    @Future 判断时间是否是未来的 @Future(message="时间必须是未来的")
    @DecimalMax 判断有精确度的数值的最大值 @DecimalMax(value = "30.50", message = "余额不能超过30.5")
    @DecimalMin 判断有精确度的数值的最小值 @DecimalMin(value = "1.50", message = "余额不能低于1.5")
    @AssertTrue 布尔属性必须是true @AssertTrue(message="信息")
    @AssertFlase 布尔属性必须是false @AssertFlase(message="信息")
    @Size 限定集合大小 @Size(min=10,max=32)

    ...

    相关文章

      网友评论

          本文标题:SpringBoot对表单做数据校验

          本文链接:https://www.haomeiwen.com/subject/ohcjdqtx.html