SpringBoot之表单验证@Valid

原文:   http://blog.csdn.net/huangbaokang/article/details/78122794?locationNum=4&fps=1


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

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

要求姓名不能为空,年龄必须是不小于18 ; 
我们先新建一个Student实体

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;
    }

}
  • 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

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

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

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

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

service接口类:

package com.java1234.service;

import com.java1234.entity.Student;

/**
 * 学生Service接口
 * @author user
 *
 */
public interface StudentService {

    /**
     * 添加学生
     */
    public void add(Student student);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

service接口实现类:

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);
    }
}
  • 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

controller控制器类:

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 "添加成功!";
        }
    }
}
  • 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

studentAdd页面

<!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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值