1、本文采用hibernate-validator进行参数校验
a、引入依赖
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency>
b、可以在pom.xml右击查看是否已经存在该依赖。存在的话其实可以不用添加,例如本人在之前加了Oauth2的依赖,而Oauth2的依赖已经包含了hibernate-validator,所以就不用再次添加;相关查看操作如下:
2、配置快速失败;
a、何为快速失败?快速失败就是在验证多个参数的时候,只要有一个参数出现校验失败就停止校验,继而抛出错误信息
b、
package com.cloud.member.config;
import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
/**
* Created by roto-1 on 2019/4/3.
*/
@Configuration
public class ValidationConfig {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
/**
* 设置快速失败
* @return
*/
@Bean
public Validator validator(){
ValidatorFactory validatorFactory= Validation.byProvider(HibernateValidator.class)
.configure()
.failFast(true)
.buildValidatorFactory();
Validator validator=validatorFactory.getValidator();
return validator;
}
}
3、配置异常处理
package com.cloud.member.exception;
import com.cloud.common.vo.ResultMap;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
/**
* Created by roto-1 on 2019/4/3.
*/
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* 用来处理bean validation异常
* @param ex
* @return
*/
@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
public ResultMap resolveConstraintViolationException(ConstraintViolationException ex){
Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
if(!CollectionUtils.isEmpty(constraintViolations)){
StringBuilder msgBuilder = new StringBuilder();
for(ConstraintViolation constraintViolation :constraintViolations){
msgBuilder.append(constraintViolation.getMessage()).append(",");
}
String errorMessage = msgBuilder.toString();
if(errorMessage.length()>1){
errorMessage = errorMessage.substring(0,errorMessage.length()-1);
}
return ResultMap.getFailureResult(400,errorMessage);
}
return ResultMap.getFailureResult(400,ex.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public ResultMap resolveMethodArgumentNotValidException(MethodArgumentNotValidException ex){
List<ObjectError> objectErrors = ex.getBindingResult().getAllErrors();
if(!CollectionUtils.isEmpty(objectErrors)) {
StringBuilder msgBuilder = new StringBuilder();
for (ObjectError objectError : objectErrors) {
msgBuilder.append(objectError.getDefaultMessage()).append(",");
}
String errorMessage = msgBuilder.toString();
if (errorMessage.length() > 1) {
errorMessage = errorMessage.substring(0, errorMessage.length() - 1);
}
return ResultMap.getFailureResult(400,errorMessage);
}
return ResultMap.getFailureResult(400,ex.getMessage());
}
}
4、构建校验结果实体(此处用到了lombok)
package com.cloud.member.validator;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* @author E
* @date 2019/2/26 15:26
*/
@Data
public class ValidationResult {
// 检验结果是否有错
private boolean hasErrors = false;
// 存放错误信息的Map
private Map<String, String> errorMsgMap = new HashMap<>();
// 实现通用的通过格式化字符串信息获取错误结果的msg方法
public String getErrMsg() {
return StringUtils.join(errorMsgMap.values().toArray(), ",");
}
}
5、创建校验实现
package com.cloud.member.validator;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
/**
* @author E
* @date 2019/2/26 15:35
*/
@Component
public class ValidatorImpl implements InitializingBean {
private Validator validator;
//实现检验方法并返回检验结果
public ValidationResult validate(Object bean) {
ValidationResult result = new ValidationResult();
Set<ConstraintViolation<Object>> constraintViolationSet = validator.validate(bean);
if (constraintViolationSet.size() > 0) {
//有异常
result.setHasErrors(true);
constraintViolationSet.forEach(ConstraintValidator -> {
String errMsg = ConstraintValidator.getMessage();
String propertyName = ConstraintValidator.getPropertyPath().toString();
result.getErrorMsgMap().put(propertyName, errMsg);
});
}
return result;
}
@Override
public void afterPropertiesSet() throws Exception {
this.validator = Validation.buildDefaultValidatorFactory().getValidator();
}
}