第一节:SpringBoot 之表单验证@Valid
是spring-data-jpa的功能;
 
下面是添加学生的信息例子,要求姓名不能为空,年龄大于18岁。
 
贴下代码吧:
Student实体:
package com.cy.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.NotEmpty;
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岁")
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;
}
}

StudentDao.java:

package com.cy.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.cy.entity.Student;

public interface StudentDao extends JpaRepository<Student, Integer>{

}

StudentService.java:

package com.cy.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.cy.dao.StudentDao;
import com.cy.entity.Student; @Service
public class StudentService { @Resource
private StudentDao studentDao; public void add(Student student) {
studentDao.save(student);
}
}

StudentController.java:

package com.cy.controller;

import javax.annotation.Resource;
import javax.validation.Valid;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cy.entity.Student;
import com.cy.service.StudentService; @RestController
@RequestMapping("/student")
public class StudentController { @Resource
private StudentService studentService; /**
* 添加学生
* @param student
* @return
*/
@RequestMapping("/add")
public String add(@Valid Student student, BindingResult bindingResult){
if(bindingResult.hasErrors()){
return bindingResult.getFieldError().getDefaultMessage();
}else{
studentService.add(student);
return "添加成功";
}
}
}

src/main/webapp/studentAdd.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生信息添加页面</title>
<script src="resources/jquery/jquery.min.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"/><br/>
年龄:<input type="text" id="age"/><br/>
<input type="button" onclick="submitData()" value="提交"/>
</body>
</html>

浏览器http://localhost/studentAdd.html,输入值不对,会提示:

补充验证的其他注解,这里只用了两个注解,下面列下清单,平时可以参考用;

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

spring boot学习(7) SpringBoot 之表单验证的更多相关文章

  1. Spring Boot 2 + Thymeleaf:服务器端表单验证

    表单验证分为前端验证和服务器端验证.服务器端验证方面,Java提供了主要用于数据验证的JSR 303规范,而Hibernate Validator实现了JSR 303规范.项目依赖加入spring-b ...

  2. jQuery学习之:Validation表单验证插件

    http://polaris.blog.51cto.com/1146394/258781/ 最近由于公司决定使用AJAX + Struts2来重构项目,让我仔细研究一下这两个,然后集中给同事讲讲,让每 ...

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

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

  4. SpringBoot之表单验证@Valid

    转自:https://www.cnblogs.com/chenlove/p/8708627.html SpringBoot提供了强大的表单验证功能实现,给我们省去了写验证的麻烦: 这里我们给下实例,提 ...

  5. 【jQuery基础学习】06 jQuery表单验证插件-Validation

    jQuery的基础部分前面都讲完了,那么就看插件了. 关于jQuery表单验证插件-Validation validation特点: 内置验证规则:拥有必填.数字.E-Mail.URL和信用卡号码等1 ...

  6. angular学习笔记(二十)-表单验证

    本篇主要介绍angular中的表单验证: 表单验证主要有以下一些内容: 1. required指令: 相当于html5的required属性,验证不能为空 2. ng-maxlength属性: 验证内 ...

  7. 【AngularJS学习笔记】AngularJS表单验证

    AngularJS表单验证 AngularJS提供了一些自带的验证属性 1.novalidate:添加到HTML的表单属性中,用于禁用浏览器默认的验证. 2.$dirty   表单有填写记录 3.$v ...

  8. Yii学习笔记之四(表单验证 api 翻译)

    1.表单验证 对于用户输入的全部数据,你不能信任,必须加以验证. 全部框架如此.对于yii 能够使用函数  yii\base\Model::validate()  进行验证 他会返回boolean值的 ...

  9. spring boot 学习(五)SpringBoot+MyBatis(XML)+Druid

    SpringBoot+MyBatis(xml)+Druid 前言 springboot集成了springJDBC与JPA,但是没有集成mybatis,所以想要使用mybatis就要自己去集成. 主要是 ...

随机推荐

  1. vue项目启动

    这篇文章主要用于有源码vue项目安装: 1.安装node.js环境(npm包管理器)前面博客有写到如何安装: 2.vue-cli 脚手架构建工具前面博客有写到如何安装: 3.cnpm  npm的淘宝镜 ...

  2. 形成一个zigzag数组(JPEG编码里取像素数据的排列顺序)

    面试例题:输入n,求一个nXn矩阵,规定矩阵沿45度递增,形成一个zigzag数组(JPEG编码里取像素数据的排列顺序),请问如何用C++实现? (中国台湾著名硬件公司2007年11月面试题)(自程序 ...

  3. Mysql 分区表-分区操作

    一.查看MySQL是否支持分区 1.MySQL5.6以及之前版本 show variables like '%partition%'; 2.MySQL5.7 show plugins; 二.分区表的分 ...

  4. 关于C++静态成员函数访问非静态成员变量的问题

    静态成员函数不能访问非静态成员,这是因为静态函数属于类而不是属于整个对象,静态函数中的 member可能都没有分配内存.静态成员函数没有隐含的this自变量.所以,它就无法访问自己类的非静态成员 代码 ...

  5. Python 爬虫常用库(九)

  6. MyEclipse移动开发教程:设置所需配置的iOS应用(四)

    MyEclipse个人授权 折扣低至冰点!立即开抢>> [MyEclipse最新版下载] 三.创建配置文件 Provisioning profiles授权文件应用程序在iOS设备上安装并运 ...

  7. React 源码剖析系列 - 不可思议的 react diff

      简单点的重复利用已有的dom和其他REACT性能快的原理. key的作用和虚拟节点 目前,前端领域中 React 势头正盛,使用者众多却少有能够深入剖析内部实现机制和原理. 本系列文章希望通过剖析 ...

  8. valgrind- 内存泄漏-how to install and use

    1.how to install my host computer is ARM, U need to Attention yours... valgrind下载: http://valgrind.o ...

  9. pymysql中如何将动态的插入数据库中

    data = { ', 'name': 'zengsf', 'age': 20 } table = 'students' #获取到一个以键且为逗号分隔的字符串,返回一个字符串 keys = ', '. ...

  10. width百分比

    table中的td可以在页面中直接在元素上设置width:但是li不能只能在页面中写style: <!-- <li width="20%" class="p- ...