利用validation完成对控制层的VO类进行校验
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
@Configuration
public class ValidatorConfiguration {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
//设置validator模式为快速失败返回
postProcessor.setValidator(validator());
return postProcessor;
}
@Bean
public Validator validator(){
ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
.configure()
.addProperty( "hibernate.validator.fail_fast", "true" )
.buildValidatorFactory();
Validator validator = validatorFactory.getValidator();
return validator;
}
}
这里利用springboot进行开发,@Configuration相当于之前的xml配置文件与,@Bean表示之前的一个bean类.
public class BaseVO implements Serializable {
private static final long serialVersionUID = -7265112497823460621L;
// 令牌
@NotNull(message="商家登录超时,或在其它设备登录!")
String token;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}
这里简单创建一个VO类,在token的上面使用@notnull注解,并给message赋值.
public <T> void validate(T o) {
Set<ConstraintViolation<T>> violationSet = validator.validate(o);
boolean result = true;
logger.debug(request.getRequestURI() + " validate,params is {}",o);
String message = null;
for (ConstraintViolation<T> model : violationSet) {
message = model.getMessage();
logger.warn(message);
result = false;
}
if(!result) {
throw new ValidateException(message);
}
}
将validate方法放入BaseController中,当然,这里的validator是注入进来的,代码省略了.项目在启动的时候,会校验token是否为空,当发现token为空时,set集合便有值,然后抛出异常.这时候需要定义一个全局异常.这样就可以了.
@ControllerAdvice
public class CommExceptionHandle {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Map<String, Object> handle(Exception e) {
Map<String, Object> map = new HashMap<String, Object>();
if (e instanceof ValidateException) {
map.put("status", BusinessErrorCode.PARAMS_EXCEPTION.getCode());
map.put("remark", e.getMessage());
return ResponseData.takeResponseData(map);
}else {
map.put("status", BusinessErrorCode.SYSTEM_ERROR.getCode());
map.put("remark", BusinessErrorCode.SYSTEM_ERROR.getDesc());
return ResponseData.takeResponseData(map);
}
}
}