一、添加pom架包
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.1.Final</version> </dependency>
二、在请求类上添加注解@Validated
@RestController @RequestMapping("/api/getxxx") @Validated public class xxxxxController extends BaseController {
}
三、在请求的具体方法上添加注解和参数 @Valid ,BindingResult bindingResult
public AjaxResult savexxxx( @RequestBody @Valid TestDemo demo,BindingResult bindingResult,HttpServletRequest request){
if(bindingResult.hasErrors()){
System.out.println(bindingResult.getFieldError().getDefaultMessage());
return AjaxResult.error(bindingResult.getFieldError().getDefaultMessage());
}
}
@Validated这个注解可以不加,加上之后会比@Valid这个注解显示的信息更详细