@Validated
@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(regex=,flag=) 被注释的元素必须符合指定的正则表达式
3.hiberate validation 注解
@Email 被注释的元素必须是电子邮箱地址
@Length(min=,max=) 被注释的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串的必须非空
@Range(min=,max=,message=) 被注释的元素必须在合适的范围内
@URL(protocol=,host=, port=, regexp=, flags=) 合法的url
主要区分下@NotNull @NotEmpty @NotBlank 3个注解的区别:
@NotNull 任何对象的value不能为null
@NotEmpty 集合对象的元素不为0,即集合不为空,也可以用于字符串不为null
@NotBlank 只能用于字符串不为null,并且字符串trim()以后length要大于0
用法
实体类测试,Myqxin.java
@Data
public class Myqxin {
@NotEmpty(message = "用户名不能为空")
private String username;
@Email(message = "邮箱格式有误")
private String email;
private String mobile;
}
Controller类测试
@RestController
@RequestMapping("/myqxin")
@Validated // 在类上只是校验非对象的
public class UserController {
@PostMapping("/post")
// 这种对象方式,就需要单独加上 @Validated,否则不生效
public Result<Myqxin> postTest(@Validated @RequestBody Myqxin myqxin){
System.out.println(myqxin);
return Result.ok("",myqxin);
}
@GetMapping("/get")
public Result<String> getTest(@NotBlank(message = "ID不能为空") String id){
System.out.println(id);
return Result.ok("",id);
}
}
写统一错误处理拦截器
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@Resource
private ISysErrorLogService sysErrorLogService;
/**
* 处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常
*/
@ExceptionHandler({BindException.class})
public Result<?> BindExceptionHandler(HttpServletRequest req,BindException e) {
// 从异常对象中拿到ObjectError对象
ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
insertLog(req, e, "1");
return Result.error("验证异常: "+objectError.getDefaultMessage());
}
/**
* 处理请求参数格式错误 @RequestBody上使用@Valid 实体上使用@NotNull等,验证失败后抛出的异常是MethodArgumentNotValidException异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result<?> MethodArgumentNotValidExceptionHandler(HttpServletRequest req,MethodArgumentNotValidException e) {
String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
insertLog(req, e, "1");
return Result.error(message);
}
/**
* 处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是ConstraintViolationException
*/
@ExceptionHandler(ConstraintViolationException.class)
public Result<?> ConstraintViolationExceptionHandler(HttpServletRequest req,ConstraintViolationException e) {
String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
insertLog(req, e, "1");
return Result.error(message);
}
/**
* 参数格式异常
*/
@ExceptionHandler(HttpMessageNotReadableException.class)
public Result<?> HttpMessageNotReadableExceptionHandler(HttpServletRequest req,HttpMessageNotReadableException e) {
insertLog(req, e, "1");
return Result.error("参数格式异常"+e);
}
private void insertLog(HttpServletRequest request, Exception ex, String logType) {
// 远程访问IP
String ip = IPUtils.getIpAddr(request);
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw, true));
//返回请求行中的参数部分
Map<String, String[]> parameterMap = request.getParameterMap();
String s = JSONUtil.toJsonStr(parameterMap);
// 插入异常日志到数据库
SysErrorLog log = new SysErrorLog();
log.setIp(ip);
log.setLogType(logType);
log.setParams(s);
log.setMethodName(request.getRequestURI());
log.setExceptionType(ex.getClass().getSimpleName());
// 异常详细信息
log.setExceptionMessage(sw.toString());
// 默认未读,0:为查看、1:已查看
log.setIsView("0");
log.setCreateTime(new Date());
sysErrorLogService.save(log);
}
}
测试效果
如果验证工具不能满足业务的逻辑验证可以参考