https://reflectoring.io/bean-validation-with-spring-boot/
https://github.com/thombergs/code-examples/tree/master/spring-boot/validation
https://spring.io/guides/gs/validating-form-input/
https://www.jianshu.com/p/51e8d2702ca1
spring和hibernate提供了基本的校验,输入数据不能空,整数范围等等。这可以节约我们程序的判断。
例子代码 https://github.com/wengmingdong/wmdspringtest/tree/master/validationtest
基本步骤
引入jar包
给需要校验的参数注解
如果maven引入了springboot web就包含了校验的jar包了。独立的是(spring-boot-starter-validation)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
创建controller类
普通参数校验
@RestController
@RequestMapping("/mytest/rest")
@Validated
public class MyRestParameterController {
// /mytest/rest/valid/blank?id=abc
@RequestMapping(value ="/valid/blank", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public StringvalidationParameterBlank(@RequestParam(value ="id")@Valid @NotBlank String id) {
return "hello blank " + id;
}
// /mytest/rest/valid/length?id=abc
@RequestMapping(value ="/valid/length", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public StringvalidationParameterLength(@RequestParam(value ="id")@Valid @Size(min =3, max =5) String id) {
return "hello length " + id;
}
}
对象bean校验
@RestController
@RequestMapping("/mytest/rest")
public class MyRestBeanController {
// /mytest/rest/valid/bean?userId=abc
@RequestMapping(value ="/valid/bean", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public StringvalidationParameterBean(@RequestParam(value ="id2") String id2, @Valid ValidInst validInst) {
return "hello length " + validInst.getId() +";" + validInst.getName() +";" + id2;
}
}
自定义校验
@RestController
@RequestMapping("/mytest/rest")
@Validated
public class MyRestCustomController {
// /mytest/rest/valid/custom?name=abc
@RequestMapping(value ="/valid/custom", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public StringvalidationParameterCustom(@RequestParam(value ="name")@Valid @NameValid String name) {
return "hello custom " + name;
}
}
自定义校验需要添加两个类
校验注解类
@Target({PARAMETER, FIELD })
@Retention(RUNTIME)
@Constraint(validatedBy = NameValidator.class)
@Documented
public @interface NameValid {
Stringmessage()default "名称不是abc";//"{name.invalid}";
Class[]groups()default { };
Class[]payload()default { };
}
校验类
public class NameValidator implements ConstraintValidator {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (!"abc".equalsIgnoreCase(value)) {
return false;
}
return true;
}
}
普通参数和对象参数校验配置差别是少一个@Validated注解
@RestController
@RequestMapping("/mytest/rest")
@Validated
public class MyRestParameterController {