转自:https://www.cnblogs.com/chenlove/p/8708627.html

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

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

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

我们先新建一个Student实体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.java1234.entity;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
 
@Entity
@Table(name="t_student")
public class Student {
 
    @Id
    @GeneratedValue
    private Integer id;
     
    @NotEmpty(message="姓名不能为空!")
    @Column(length=50)
    private String name;
     
    @NotNull(message="年龄不能为空!")
    @Min(value=18,message="年龄必须大于18岁!")
    @Column(length=50)
    private Integer age;
 
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public Integer getAge() {
        return age;
    }
 
    public void setAge(Integer age) {
        this.age = age;
    }
     
}

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

限制 说明
@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格式

dao接口写下:

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

service接口写下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.java1234.service;
 
import com.java1234.entity.Student;
 
/**
 * 学生Service接口
 * @author user
 *
 */
public interface StudentService {
 
    /**
     * 添加学生
     */
    public void add(Student student);
}

service接口实现类写下:

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

controller写下:

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

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

student添加页面studentAdd.html

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

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

直接点击提交

输入姓名后,提交

输入年龄5,提交

我们改成20,提交

提交通过。

SpringBoot之表单验证@Valid的更多相关文章

  1. (办公)springboot配置表单验证@Valid

    项目用到了springboot,本来很高兴,但是项目里什么东西都没有,验证,全局异常这些都需要自己区配置.最近springboot用的还是蛮多的,我还是做事情,把经验发表一下. SpringBoot提 ...

  2. spring boot学习(7) SpringBoot 之表单验证

    第一节:SpringBoot 之表单验证@Valid 是spring-data-jpa的功能:   下面是添加学生的信息例子,要求姓名不能为空,年龄大于18岁.   贴下代码吧: Student实体: ...

  3. 1-7SpringBoot之表单验证@Valid

    SpringBoot提供了强大的表单验证功能实现,给我们省去了写验证的麻烦: 这里我们给下实例,提交一个有姓名和年龄的表单添加功能, 要求姓名不能为空,年龄必须是不小于18 : 我们先新建一个Stud ...

  4. SpringBoot整合表单验证注解@Validated,以及分组验证

    首先引入jar包 <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate ...

  5. SpringBoot(五)_表单验证

    SpringBoot(五)_表单验证 参数校验在我们日常开发中非常常见,最基本的校验有判断属性是否为空.长度是否符合要求等,在传统的开发模式中需要写一堆的 if else 来处理这些逻辑,很繁琐,效率 ...

  6. @valid表单验证demo

    springMVC 表单验证demo  视图层使用的是jsp

  7. Spring Boot笔记八:表单验证

    所谓的表单验证,就是为了防止用户乱输入的,这个问题前端的HTML5就可以判断了,其实不需要后端来验证,这里还是讲一下后端验证 首先,我们的Person类,我们加上一些表单验证的注释,如下: packa ...

  8. Spring进行表单验证

    转自:https://www.tianmaying.com/tutorial/spring-form-validation 开发环境 IDE+Java环境(JDK 1.7或以上版本) Maven 3. ...

  9. jQuery学习之路(8)- 表单验证插件-Validation

    ▓▓▓▓▓▓ 大致介绍 jQuery Validate 插件为表单提供了强大的验证功能,让客户端表单验证变得更简单,同时提供了大量的定制选项,满足应用程序各种需求.该插件捆绑了一套有用的验证方法,包括 ...

随机推荐

  1. Vue2-Editor 使用

    Vue-Editor底层采取的是quill.js,而quill.js采用的是html5的新属性classList,所以版本低于ie10会报错“无法获取未定义或 null 引用的属性‘confirm’” ...

  2. JS排序之快速排序

    JS排序之快速排序 一个数组中的数据,选择索引为(2/数组长度)的那个数据作为基数,数组中的其他数据与它对比,比它数值小的放在做数组,比它数值大的放在右数组,最后组合 左数组+基数+右数组,其中,左数 ...

  3. js-var变量作用域

    看代码: var a=10; function fn1(){ alert(a); var a=20; alert(a); } 运行结果:undefined 和 20 注意: 在函数内,变量如没用var ...

  4. 课上练习 script

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  5. DataTable如何去除重复的行

    两种方法1 数据库直接去除重复select distinct * from 表名去除了重复行distinct 2 对 DataTable直接进行操作DataTable dt=db.GetDt(&quo ...

  6. css单双行样式

    #random_box li:nth-child(odd) {//双行 background: #fff5c4; } #random_box li:nth-child(even) {//单行 back ...

  7. jquery-pjax使用说明

    pjax = pushState + ajax .--. / \ ## a a ( '._) |'-- | _.\___/_ ___pjax___ ."\> \Y/|<'. '. ...

  8. Fedora Atomic Host 使用中的几个坑

    做成U盘启动:必须用配套工具写U盘,否则安装时各种timeout Cockpit中文页面会导致登录后页面空白的bug,解决办法是更改浏览器首选语言 没有yum,无法下载网页浏览器w3m,Pydio c ...

  9. apicloud UISearchBar 使用方法

    app中经常会有搜索的页面. 大概逻辑是,一般来说首页有一个搜索的图,点击之后跳转到一个搜索的页面,在这个页面做搜索. 正常代码逻辑 <body> <a class="bu ...

  10. 解析MYsql写的表达式

    今天遇到个问题,Sql中直接写的是复杂表达式,如何解析呢? round(((0.00579049505+0.00006600324*JING_JIE^2*SHU_GAO-0.00000046921*J ...