springmvc springboot 简单轻量好用的参数验证。支持基本类型查参数验证。支持自定义注解的参数验证。使用简单方便。
<dependency> <groupId>com.github.fashionbrot</groupId> <artifactId>mars-validated</artifactId> <version>1.0.0</version> </dependency>
@SpringBootApplication @EnableValidatedConfig(fileName = "valid_zh_CN") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
@Component @Configuration @EnableValidatedConfig(fileName = "valid_zh_CN") public class Config { }
@Controller public class DemoController { @Autowired private TestService testService; @RequestMapping("/emailCheck") @ResponseBody @Validated //注意此处 public String demo(@Email String abc,){ return testService.test(abc); } } @Controller public class DemoController { @Autowired private TestService testService; @RequestMapping("/idcardCheck") @ResponseBody @Validated public String demo(IdCardModel idCardModel){ return testService.test("ac"); } @RequestMapping("/idcardCheck2") @ResponseBody public String demo2(IdCardModel idCardModel){ return testService.test2("ac"); } } **此处支持多继承验证*** public class IdCardModel extends BaseModel{ @IdCard private String idCardModel; public String getIdCardModel() { return idCardModel; } public void setIdCardModel(String idCardModel) { this.idCardModel = idCardModel; } } @Service public class TestService{ @Validated public void test2(@IdCard String abc){ } }
拦截 com.fashion.spv.validated.exception.ValidatedException
@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ValidatedException.class) @ResponseStatus(HttpStatus.OK) public RespMessage ValidationException(ValidatedException e){ return new RespMessage(-100,e.getMsg()); } }
spring4.0 及以上 jdk1.8 及以上
1、实现 ConstraintValidator 此接口 2、自定义注解如下: CustomConstraintValidator.class,CustomConstraintValidator2.class 实现类可多个,至少有一个 @Documented @Target({ElementType.FIELD, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = {CustomConstraintValidator.class,CustomConstraintValidator2.class}) public @interface Custom { String msg() default "com.spv.valid.Custom.msg"; int min(); } 3、代码实现 public class CustomConstraintValidator implements ConstraintValidator<Custom,String> { @Override public boolean isValid(Custom custom,String var1) { /** * 自定义方法 */ int min=custom.min(); /** * value */ System.out.println(var1); /** * return true 则验证成功 false 验证失败 */ return true; } }