第一节: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. centos7 sftp设置后 ssh 启动失败 原因分析

    大多数人 在 设置SFTP 使用时,会在 ../sshd_config中添加如下内容: ------------------------------- Subsystem sftp internal- ...

  2. <NET CLR via c# 第4版>笔记 第13章 接口

    13.1 类和接口继承 13.2 定义接口 C#用 interface 关键字定义接口.接口中可定义方法,事件,无参属性和有参属性(C#的索引器),但不能定义任何构造器方法,也不能定义任何实例字段. ...

  3. 【数据库】MFC ODBC(二)

    三.CRecordset类 1.IsBOF与IsEOF (1)IsBOF 如果记录集没有记录,或已经向前游动到第一个记录之前,则返回非零:否则返回0.详细说明如下: 1)访问Open函数之后,如果记录 ...

  4. Spring的DAO模块

    Spring的DAO模块提供了对JDBC.Hibernate.JDO等DAO层支持. DAO模块依赖 commons-pool.jar.commons-collections.jar package ...

  5. CentOS7安装OpenStack(Rocky版)-09.安装Cinder存储服务组件(控制节点)

    本文分享openstack的Cinder存储服务组件,cinder服务可以提供云磁盘(卷),类似阿里云云盘 ----------------------- 完美的分隔线  -------------- ...

  6. nginx服务相关操作

    安装目录 和大多软件一样一般安装在 /usr/local/ 目录下 /usr/local/ 命令man Usage: nginx [-?hvVt] [-s signal] [-c filename] ...

  7. Wireless Network 并查集

    An earthquake takes place in Southeast Asia. The ACM (Asia Cooperated Medical team) have set up a wi ...

  8. spring boot 热部署devtools实现

    1.devtools spring为开发者提供了一个名为spring-boot-devtools的模块来使Spring Boot应用支持热部署,提高开发者的开发效率,无需手动重启Spring Boot ...

  9. gridview 自动序号 合计

    第一种方式,直接在Aspx页面GridView模板列中.这种的缺点是到第二页分页时又重新开始了. <asp:TemplateField HeaderText="序号" Ins ...

  10. Windows中的SID详解

    SID详解前言 SID也就是安全标识符(Security Identifiers),是标识用户.组和计算机帐户的唯一的号码.在第一次创建该帐户时,将给网络上的每一个帐户发布一个唯一的 SID.Wind ...