第十四篇: Spring Boot使用校验框架validation校验

Spring Boot在内部通过集成hibernate-validation已经实现了JSR-349验证规范接口,在Spring Boot项目中只要直接使用就行了。
一般用在Controller中用于验证前端传来的参数。

验证分两种:对封装的Bean进行验证  或者  对方法简单参数的验证。

validation与 springboot 结合

1. bean 中添加标签

部分代码: 
标签需要加在属性上,@NotBlank 标签含义文章末尾有解释


package com.example.validation.domain;

import javax.validation.constraints.Pattern;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;

public class User {
	@NotBlank(message = "用户名称不能为空。")
	private String name;

	@Range(max = 150, min = 1, message = "年龄范围应该在1-150内。")
	private Integer age;

	@NotEmpty(message = "密码不能为空")
	@Length(min = 6, max = 8, message = "密码长度为6-8位。")
	@Pattern(regexp = "[a-zA-Z]*", message = "密码不合法")
	private String password;

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

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

2. Controller中开启验证

在Controller 中 请求参数上添加@Validated 标签开启验证


package com.example.validation.web;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.validation.domain.User;

@RestController
public class ValidatorController {

	private static final Logger log = LoggerFactory.getLogger(ValidatorController.class);

	/**
	 * 验证框架使用测试
	 * 
	 * @param user
	 * @param result
	 */
	@PostMapping("v/t1.json")
	public void v1(@Validated User user, BindingResult result) {
		StringBuilder sBuilder = new StringBuilder();
		sBuilder.append("\n");
		if (result.hasErrors()) {
			List<ObjectError> list = result.getAllErrors();
			for (ObjectError error : list) {
				log.info(error.getCode() + "---" + error.getArguments() + "---" + error.getDefaultMessage());
				System.out.println(error.toString());
				sBuilder.append(error.getDefaultMessage());
				sBuilder.append("\n");
			}
		}
		log.info(sBuilder.toString());
	}
}

3. resource 下新建错误信息配置文件

在resource 目录下新建提示信息配置文件“ValidationMessages.properties“

注意:名字必须为“ValidationMessages.properties“ 因为SpringBoot自动读取classpath中的ValidationMessages.properties里的错误信息
  • 1
  • 2

ValidationMessages.properties 文件的编码为ASCII。数据类型为 key value 。key“user.name.notBlank“为第一步 bean的标签 大括号里面对应message的值

value 为提示信息 ,但是是ASCII 。(内容为“名字不能为空“)

这里写图片描述

4. 自定义异常处理器,捕获错误信息

当验证不通过时会抛异常出来,异常的message 就是 ValidationMessages.properties 中配置的提示信息。此处定义异常处理器。捕获异常信息(因为验证不通过的项可能是多个所以统一捕获处理),并抛给前端。(此处是前后端分离开发)

    public void MethodArgumentNotValidException(Exception ex, HttpServletRequest request, HttpServletResponse response) {
        logger.error( ":" + CommonUtil.getHttpClientInfo(request), ex);
        MethodArgumentNotValidException c = (MethodArgumentNotValidException) ex;
        List<ObjectError> errors =c.getBindingResult().getAllErrors();
        StringBuffer errorMsg=new StringBuffer();
        errors.stream().forEach(x -> errorMsg.append(x.getDefaultMessage()).append(";"));
        pouplateExceptionResponse(response, HttpStatus.INTERNAL_SERVER_ERROR, errorMsg.toString());
    }


 private void pouplateExceptionResponse(HttpServletResponse response, HttpStatus errorCode, String errorMessage) {
        try {
            response.sendError(errorCode.value(), errorMessage);
        } catch (IOException e) {
            logger.error("failed to populate response error", e);
        }
    }

5. 附上部分标签含义

Bean Validation 中内置的 constraint

           注解                                      作用

@Valid 被注释的元素是一个对象,需要检查此对象的所有字段值
@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) 被注释的元素必须符合指定的正则表达式
Hibernate Validator 附加的 constraint

注解 作用
@Email 被注释的元素必须是电子邮箱地址
@Length(min=, max=) 被注释的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串的必须非空
@Range(min=, max=) 被注释的元素必须在合适的范围内
@NotBlank 被注释的字符串的必须非空
@URL(protocol=,
host=,    port=, 
regexp=, flags=)
被注释的字符串必须是一个有效的url
@CreditCardNumber
被注释的字符串必须通过Luhn校验算法,
银行卡,信用卡等号码一般都用Luhn
计算合法性
@ScriptAssert
(lang=, script=, alias=)
要有Java Scripting API 即JSR 223 
("Scripting for the JavaTM Platform")的实现
@SafeHtml
(whitelistType=, 
additionalTags=)
classpath中要有jsoup包

hibernate补充的注解中,最后3个不常用,可忽略。

主要区分下@NotNull  @NotEmpty  @NotBlank 3个注解的区别:

@NotNull           任何对象的value不能为null

@NotEmpty       集合对象的元素不为0,即集合不为空,也可以用于字符串不为null

@NotBlank        只能用于字符串不为null,并且字符串trim()以后length要大于0

hibernate注解详细:http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/

源码下载地址:https://gitee.com/zhmal/spring-boot-samples/tree/master/spring-boot-sample-validation

猜你喜欢

转载自blog.csdn.net/mzh_cn/article/details/80637015