zoukankan      html  css  js  c++  java
  • SpringBoot之表单验证Valid

    SpringBoot提供了强大的表单验证功能实现,给我们省去了写验证的麻烦;

    这里我们给下实例,提交一个有姓名和年龄的表单添加功能,

    要求姓名不能为空,年龄必须是不小于18 ;

    我们先新建一个Student实体

    Student.java

     1 package com.hik.entity;
     2 
     3 import javax.persistence.Column;
     4 import javax.persistence.Entity;
     5 import javax.persistence.GeneratedValue;
     6 import javax.persistence.Id;
     7 import javax.persistence.Table;
     8 import javax.validation.constraints.Min;
     9 import javax.validation.constraints.NotNull;
    10 
    11 import org.hibernate.validator.constraints.NotEmpty;
    12 
    13 @Entity//类对应实体
    14 @Table(name="t_student")//实体映射的表
    15 public class Student {
    16     
    17     @Id//主键
    18     @GeneratedValue//主键生成策略
    19     private Integer id;
    20     
    21     @NotEmpty(message="姓名不能为空!")//验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)
    22     @Column(length=50)//设置字段属性
    23     private String name;
    24     
    25     @NotNull(message="年龄不能为空!")//限制必须不为null
    26     @Min(value=18,message="年龄必须大于18岁!")//限制必须为一个不小于指定值的数字
    27     @Column(length=50)//设置字段属性
    28     private Integer age;
    29 
    30     public Integer getId() {
    31         return id;
    32     }
    33 
    34     public void setId(Integer id) {
    35         this.id = id;
    36     }
    37 
    38     public String getName() {
    39         return name;
    40     }
    41 
    42     public void setName(String name) {
    43         this.name = name;
    44     }
    45 
    46     public Integer getAge() {
    47         return age;
    48     }
    49 
    50     public void setAge(Integer age) {
    51         this.age = age;
    52     }
    53     
    54     
    55 }
    View Code

    注意:整数都用包装类Integer

    这里只用了两个注解,下面列下清单,平时可以参考用;

    限制说明
    @Null 限制只能为null
    @NotNull 限制必须不为null
    @AssertFalse 限制必须为false
    @AssertTrue 限制必须为true
    @DecimalMax(value) 限制必须为一个不大于指定值的数字
    @DecimalMin(value) 限制必须为一个不小于指定值的数字
    @Digits(integer,fraction) 限制必须为一个小数,且整数部分的位数不能超过integer,小数部分的位数不能超过fraction
    @Future 限制必须是一个将来的日期
    @Max(value) 限制必须为一个不大于指定值的数字
    @Min(value) 限制必须为一个不小于指定值的数字
    @Past 限制必须是一个过去的日期
    @Pattern(value) 限制必须符合指定的正则表达式
    @Size(max,min) 限制字符长度必须在min到max之间
    @Past 验证注解的元素值(日期类型)比当前时间早
    @NotEmpty 验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)
    @NotBlank 验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格
    @Email 验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式

    StudentDao接口:

     1 package com.hik.dao;
     2 
     3 import org.springframework.data.jpa.repository.JpaRepository;
     4 
     5 import com.hik.entity.Student;
     6 
     7 /**
     8  * 学生Dao接口
     9  * @author jed
    10  *
    11  */
    12 public interface StudentDao extends JpaRepository<Student, Integer>{
    13 
    14 }
    View Code

    StudentService接口写下:

     1 package com.hik.service;
     2 
     3 import com.hik.entity.Student;
     4 
     5 /**
     6  * 学生Service接口
     7  * @author jed
     8  *
     9  */
    10 public interface StudentService {
    11 
    12     public void add(Student student);
    13 }
    View Code

    StudentServiceImpl接口实现类写下:

     1 package com.hik.service.impl;
     2 
     3 import javax.annotation.Resource;
     4 
     5 import org.springframework.stereotype.Service;
     6 
     7 import com.hik.dao.StudentDao;
     8 import com.hik.entity.Student;
     9 import com.hik.service.StudentService;
    10 
    11 /**
    12  * 学生Service实现类
    13  * @author jed
    14  *
    15  */
    16 @Service(value="studentService")
    17 public class StudentServiceImpl implements StudentService{
    18 
    19     @Resource
    20     private StudentDao studentDao;
    21     @Override
    22     public void add(Student student) {
    23         studentDao.save(student);
    24     }
    25 
    26 }
    View Code

    StudentController写下:

     1 package com.hik.Controller;
     2 
     3 import javax.annotation.Resource;
     4 import javax.validation.Valid;
     5 
     6 import org.springframework.validation.BindingResult;
     7 import org.springframework.web.bind.annotation.PostMapping;
     8 import org.springframework.web.bind.annotation.RequestMapping;
     9 import org.springframework.web.bind.annotation.ResponseBody;
    10 import org.springframework.web.bind.annotation.RestController;
    11 
    12 import com.hik.entity.Student;
    13 import com.hik.service.StudentService;
    14 
    15 /**
    16  * 学生控制类
    17  * @author jed
    18  *
    19  */
    20 @RestController
    21 @RequestMapping("/student")
    22 public class StudentController {
    23     
    24     @Resource
    25     private StudentService studentService;
    26 
    27     /**
    28      * 添加图书
    29      * @param student
    30      * @param bindingResult
    31      * @return
    32      */
    33     @ResponseBody
    34     @PostMapping("/add")
    35     public String add(@Valid Student student,BindingResult bindingResult) {
    36         if(bindingResult.hasErrors()) {
    37             return bindingResult.getFieldError().getDefaultMessage();
    38         }else {
    39             studentService.add(student);
    40             return "添加成功!";
    41         }
    42     }
    43 }
    View Code

    add方法里 实体前要加@Valid 假如字段验证不通过,信息绑定到后面定义的BindingResult;

    student添加页面studentAdd.html

     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4 <meta charset="UTF-8">
     5 <title>学生信息添加页面</title>
     6 <script src="jquery-1.11.1.js"></script>
     7 <script type="text/javascript">
     8     function submitData(){
     9         $.post("/student/add",{name:$("#name").val(),age:$("#age").val()},
    10                 function(result){
    11                     alert(result);
    12                 }
    13         );
    14     }
    15 </script>
    16 </head>
    17 <body>
    18 姓名:<input type="text" id="name" name="name"/>
    19 年龄:<input type="text" id="age" name="age"/>
    20 <input type="button" value="提交" onclick="submitData()"/>
    21 </body>
    22 </html>
    View Code

    浏览器请求:http://localhost/studentAdd.html

    直接点击提交

    输入年龄12后,提交

    输入大于18,输入20,提交

    输入姓名后,提交

    提交通过。

  • 相关阅读:
    springboot 整合 mybatis plus
    Centos7下安装Docker
    idea 将项目打包成 docker 镜像 推送到 阿里云
    Windows10 使用 docker toolbo x安装 docker
    js 修改 url 但不刷新页面
    MySQL-建数据库的字符集与排序规则说明
    7.Redis 缓存过期处理与内存淘汰机制
    6.Redis 主从复制原理总结
    5.Redis 持久化
    4.Springboot整合Redis
  • 原文地址:https://www.cnblogs.com/jedjia/p/valid.html
Copyright © 2011-2022 走看看