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

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

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

我们先新建一个Student实体

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接口写下:

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

 
import com.java1234.entity.Student;
 
/**
 * 学生Dao接口
 * @author user
 *
 */
public interface StudentDao extends JpaRepository<Student, Integer>{
 
}
 
service接口写下:
 
import com.java1234.entity.Student;

 
/**
 * 学生Service接口
 * @author user
 *
 */
public interface StudentService {
 
    /**
     * 添加学生
     */
    public void add(Student student);
}
 
service接口实现类写下:
 
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写下:
 
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

<!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>
 
 
 

直接点击提交

输入姓名后,提交

输入年龄5,提交

我们改成20,提交

提交通过。

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

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

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

  2. SpringBoot之表单验证@Valid

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

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

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

  4. @valid表单验证demo

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

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

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

  6. 玩转spring boot——AOP与表单验证

    AOP在大多数的情况下的应用场景是:日志和验证.至于AOP的理论知识我就不做赘述.而AOP的通知类型有好几种,今天的例子我只选一个有代表意义的“环绕通知”来演示. 一.AOP入门 修改“pom.xml ...

  7. ASP.NET MVC5+EF6+EasyUI 后台管理系统(33)-MVC 表单验证

    系列目录 注:本节阅读需要有MVC 自定义验证的基础,否则比较吃力 一直以来表单的验证都是不可或缺的,微软的东西还是做得比较人性化的,从webform到MVC,都做到了双向验证 单单的用js实现的前端 ...

  8. jQuery Validate 表单验证 — 用户注册简单应用

    相信很多coder在表单验证这块都是自己写验证规则的,今天我们用jQuery Validate这款前端验证利器来写一个简单的应用. 可以先把我写的这个小demo运行试下,先睹为快.猛戳链接--> ...

  9. jquery validate表单验证插件-推荐

    1 表单验证的准备工作 在开启长篇大论之前,首先将表单验证的效果展示给大家.     1.点击表单项,显示帮助提示 2.鼠标离开表单项时,开始校验元素  3.鼠标离开后的正确.错误提示及鼠标移入时的帮 ...

随机推荐

  1. httpClient简单封装

    package com.Interface.util; import java.util.Iterator; import java.util.Map; import org.apache.commo ...

  2. Windowserver2012服务器激活方法(亲测可用)---转载

    Windowserver2012服务器激活方法(亲测可用)原创꧁刘向洋꧂ 最后发布于2019-03-12 14:46:45 阅读数 5124  收藏展开激活方式 slmgr /ipk D2N9P-3P ...

  3. inline-block,真的懂吗

    曾几何时,display:inline-block 已经深入「大街小巷」,随处可见 「display:inline-block; *display:inline; *zoom:1; 」这样的代码.如今 ...

  4. 短信通道——阿里大鱼(java)

    综述            注:本文写于2017年6月22日升级之后. 使用阿里大鱼发送短信已经成为一种趋势,因为权威,而且价格也比较适中,被越来越多的公司所采用.在介绍阿里大鱼发送短信之前,首先得拥 ...

  5. JDBC连接MySql例子

    1.注册MySql连接驱动 2.设置连接MySql连接字符串.用户名和密码 3.获取数据库连接 代码如下: // 加载驱动 Class.forName("com.mysql.jdbc.Dri ...

  6. leetcode菜鸡斗智斗勇系列(7)--- 用最小的时间访问所有的节点

    1.原题: https://leetcode.com/problems/minimum-time-visiting-all-points/ On a plane there are n points ...

  7. php 随机生成汉字

    function getChar($num) // $num为生成汉字的数量 { $b = ''; for ($i=0; $i<$num; $i++) { // 使用chr()函数拼接双字节汉字 ...

  8. JavaScript 数字

    数字(Number)也称为数值或数. 数值直接量 当数字直接出现在程序中时,被称为数值直接量.在 JavaScript 程序中,直接输入的任何数字都被视为数值直接量. 示例1 数值直接量可以细分为整型 ...

  9. 【转载】Eclipse vs IDEA快捷键对比大全(win系统)

    花了几天时间熟悉IDEA的各种操作,将各种快捷键都试了一下,感觉很是不错! 以下为我整理了一下开发过程中经常用的一些Eclipse快捷键与IDEA的对比,方便像我一样使用Eclipse多年但想尝试些改 ...

  10. C语言入门---第七章 C语言函数

    函数就是一段封装好的,可以重复使用的代码,它使得我们的程序更加模块化,不需要编写大量重复的代码.函数可以提前保存起来,并给它起一个独一无二的名字,只要知道它的名字就能使用这段代码.函数还可以接收数据, ...