接着上一章的,接下来我们所写的校验工具-BeanValidator开发,好了跟着我们下面的代码来实现:
首先我们需要先在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.3.6.Final</version> </dependency>
引入这两个依赖之后我们就可以写自己的validator了
在我们的util包下创建一个类BeanValidator:
package cn.oyc.util; import cn.oyc.exception.ParamException; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.commons.collections.MapUtils; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import java.util.*; 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]); } } public static void check(Object param) throws ParamException{ Map<String,String> map = BeanValidator.validateObject(param); if (MapUtils.isNotEmpty(map)){ throw new ParamException(map.toString()); } } }
编写如下代码后我们可以创建一个测试的值,添加包param,类为TestVo:
package cn.oyc.param; import lombok.Getter; import lombok.Setter; import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.util.List; @Getter @Setter public class TestVo { @NotBlank private String msg; @NotNull private Integer id; @NotEmpty private List<String> str; }
在到我们的exception包下建一个ParamException类
package cn.oyc.exception; public class ParamException extends RuntimeException { public ParamException() { super(); } public ParamException(String message) { super(message); } public ParamException(String message, Throwable cause) { super(message, cause); } public ParamException(Throwable cause) { super(cause); } protected ParamException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
这里我们还需要在打开pom.xml引入我们常用的工具类包:
<!-- tools --> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.2</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.13</version> </dependency>
然后在我们的TestController下写测试代码
package cn.oyc.controller; import cn.oyc.common.JsonData; import cn.oyc.common.SpringExceptionResolver; import cn.oyc.exception.ParamException; import cn.oyc.param.TestVo; import cn.oyc.util.BeanValidator; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.MapUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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("/text") @Slf4j public class TestController { private final Logger logger = LoggerFactory.getLogger(TestController.class); @RequestMapping("/hello.json") @ResponseBody public JsonData hello(){ logger.info("hello"); return JsonData.success("hello,permission"); } @RequestMapping("/validate.json") @ResponseBody public JsonData validate(TestVo vo) throws ParamException { logger.info("validate"); BeanValidator.check(vo); return JsonData.success("test validate"); } }
校验工具这一块我们就讲到这里了,后续会持续更新
原文地址:https://www.cnblogs.com/Myoyc/p/12231517.html
时间: 2024-10-08 02:53:31