pom.xml导入maven坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
用法:
在controller层开启校验,在类上使用注解@Validated
验证参数长度大于3。在方法中参数上加上@Lenght(min=3)
用法:
@Validated
@RestController
Public class Student{
@PostMapping(“/findall”)
Public String findall ( @Lenght(min=3) String username ){
return “”;
}
}
处理输入不符合条件报错问题:
定义一个全局异常处理类,用于处理controller层出现的异常
@ControllerAdvice
Public class ValidationController{
@ResponseBody
@ExceptionHandler(ConstrainViolationException.class)
Public String error(ValidationException e){
Return e.getMessage();
}
}
如果接受的是对象类型,需要在实体类中进行配置
@Validated
@RestController
Public class Student{
@PostMapping(“/findall”)
Public String findall ( @Valid Student student ){
return “”;
}
}
实体类
Public class Student{
@Length(min=3)
String username;
String password;
}