一、jar包的准备
<!-- JSR303数据校验的jar包5个 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.3.Final</version>
</dependency>
<dependency>
<groupId>com.fasterxml</groupId>
<artifactId>classmate</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>5.1.3.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.3.0.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
二、JSR303的常用注解列表


三、使用方法
1、需要在Spring配置文件中添加
<mvc:annotation-driven></mvc:annotation-driven>
2、在Controller层的方法中添加校验
@RequestMapping("testDateFormat") //BindingResult必须跟在需要校验的对象参数后面,否则无法获取错误信息 @Valid为校验注解,该参数使用该类里的校验注解
public String testDateFormat(@Valid Student stu,BindingResult result,Map<String,Object> map) {
System.out.println(stu);
//当格式匹配出错时,获取错误信息,该方法可以抓取异常,避免前端404
if(result.getErrorCount()>0) {
for(FieldError error:result.getFieldErrors()) {
System.out.println(error.getDefaultMessage());
}
map.put("errors", result.getFieldErrors()); //通过map将错误信息传给request域,在前端显示
}
return "success";
}
注意:
indingResult必须跟在需要校验的对象参数后面,否则无法获取错误信息;
来源:https://www.cnblogs.com/709539062rao/p/12551655.html