背景
Spring Boot 引入Hibernate Validator 机制来支持 JSR-303 验证规范
实现
请求参数model类:
package com.wzq.test.model;
import lombok.Data;
import org.springframework.stereotype.Component;
import javax.validation.constraints.*;
import java.util.Date;
/**
* @description:
* @author: Wzq
* @create: 2020-01-17 15:17
*/
@Component
@Data
public class UserModel {
//@NotEmpty :不能为null,且Size>0
//@NotNull:不能为null,但可以为empty,没有Size的约束
//@NotBlank:只用于String,不能为null且trim()之后size>0
@NotBlank(message = "用户名称不能为空!")
private String userName;
@NotNull(message = "age不能为null!")
@Min(value = 1, message = "最小值为1") // 最小值为1
@Max(value = 88, message = "最大值为88") // 最大值88
//@Range(min = 1, max = 888, message = "范围为1至888") // 限定范围
private Integer age;
//@Future(message = "需要一个将来日期") // 只能是将来的日期
// @Past //只能去过去的日期
//@DateTimeFormat(pattern = "yyyy-MM-dd") // 日期格式化转换
@NotNull(message = "日期不能为null!")
private Date date;
@Email(message = "邮箱格式错误!")
private String email;
@NotNull // 不能为空
@DecimalMin(value = "0.1") // 最小值0.1元
@DecimalMax(value = "10000.00") // 最大值10000元
private Double money = null;
}
Controller层代码:
@GetMapping("test")
@ResponseBody
public Object test(@Valid UserModel userModel){
return userModel;
}
注意添加@Valid 注解开启验证!
捕获验证参数异常
全局异常处理类
package com.wzq.config.exception;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* @description: 全局异常处理类
* @author: Wzq
* @create: 2019-12-26 11:01
*/
@RestControllerAdvice
public class GlobalExceptionAdvice {
/**
* 指定拦截异常的类型
*
* @param e
* @return json格式类型
*/
@ExceptionHandler({Exception.class}) //指定拦截异常的类型
public Object customExceptionHandler(Exception e) {
//打印异常日志
e.printStackTrace();
//非空验证异常
if(e instanceof BindException){
BindException bindException = (BindException) e;
String msg = bindException.getBindingResult().getFieldError().getDefaultMessage();
return msg;
}
return "系统异常";
}
}
成功
常用的注解
@Null 被注释的元素必须为null
@NotNull 被注释的元素不能为null
@AssertTrue 被注释的元素必须为true
@AssertFalse 被注释的元素必须为false
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max,min) 被注释的元素的大小必须在指定的范围内。
@Digits(integer,fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past 被注释的元素必须是一个过去的日期
@Future 被注释的元素必须是一个将来的日期
@Pattern(value) 被注释的元素必须符合指定的正则表达式。
@Email 被注释的元素必须是电子邮件地址
@Length 被注释的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串必须非空
@Range 被注释的元素必须在合适的范围内