在后端开发时,不可避免的需要处理一些校验, 如果是写if-else这种代码去校验, 那会有一大段这样的代码。不过还好有个校验插件:javax.validation.validation-api,不过一般会引用hibernate的校验组件:org.hibernate.hibernate-validator, 它已经引用了validation-api组件。
首先pom.xml引入依赖
<!-- validator -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency>
可能会出现这个错误:
javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'
添加依赖:
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
Spring配置注入bean
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
自己的Violation实体
这里使用的Lombok获取get和set,使用的@Getter注解 @Setter注解
import java.util.List;
/**
* @Auther: Summer
* @Date: 2019-01-05 11:35
* @Description: 测试实体类
* @versions:1.0
*/
@Getter
@Setter
public class TestVo {
@NotBlank // @NotBlank 必须是String类型的
private String msg;
@NonNull // @NotNull:不能为null,但可以为empty,没有Size的约束
private String id;
private List<String> str;
}
@NotEmpty 用在集合类上面
@NotBlank 用在String上面
@NotNull 用在基本类型上
如果在基本类型上面用NotEmpty或者NotBlank 会出现下面的错
javax.validation.UnexpectedTypeException: No validator could be found for type: java.lang.Integer
接口工具类util
/**
* @Auther: Summer
* @Date: 2019-01-05 11:00
* @Description: 接口效验
* @versions:1.0
*/
public class BeanValidator {
private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
public static <T> Map<String, String> validate(T t, Class... groups) {
Validator validator = validatorFactory.getValidator();
Set validateResult = validator.validate(t, groups);
if (validateResult.isEmpty()) { //如果校验有值
return Collections.emptyMap();
} else {
LinkedHashMap errors = Maps.newLinkedHashMap();
Iterator iterator = validateResult.iterator();
while (iterator.hasNext()) {
ConstraintViolation violation = (ConstraintViolation)iterator.next();
errors.put(violation.getPropertyPath().toString(), violation.getMessage());
}
return errors;
}
}
public static Map<String, String> validateList(Collection<?> collection) {
Preconditions.checkNotNull(collection); //判断是否为空
Iterator iterator = collection.iterator();
Map errors;
do {
if (!iterator.hasNext()) {
return Collections.emptyMap();
}
Object object = iterator.next();
errors = validate(object, new Class[0]);
} while (errors.isEmpty());
return errors;
}
public static Map<String, String> validateObject(Object first, Object... objects) {
if (objects != null && objects.length > 0) {
return validateList(Lists.asList(first, objects));
} else {
return validate(first, new Class[0]);
}
}
通过controller 验证Slf4j的log.info打印日志信息验证是否成功
package com.mmall.controller;
import com.mmall.common.JsonDate;
import com.mmall.param.TestVo;
import com.mmall.util.BeanValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Map;
@Controller
@RequestMapping("/test")
@Slf4j
public class TestController {
@RequestMapping("/validate.json")
@ResponseBody
public JsonDate validate(TestVo vo){
log.info("validate");
try {
Map<String,String> map = BeanValidator.validateObject(vo);
if(map != null && map.entrySet().size() >0){
for (Map.Entry<String,String> entry: map.entrySet()){
log.info("{}->{}",entry.getKey(),entry.getValue());
}
}
}catch (Exception e){
}
return JsonDate.success("test,validate");
}
}
打印结果:
附注解图: