效验器:
1. 效验器依赖
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
2. 实体类
public class UserInfo {
@NotNull(message = "编号不能为空")
private Integer user_id;
@NotNull
@Length(min = 2,max = 8,message = "用户名不能少于2位大于8位")
private String user_email;
@Pattern(regexp = "",message = "手机号格式不正确")
private String user_phone;
private String user_address;
@Pattern(regexp = "",message = "身份证号不正确")
private String user_cardCode;
//省略get/set方法...
}
3. 控制器
@RequestMapping("/validate")
public String validate(@Valid UserInfo info, BindingResult bindingResult){
//如果有异常信息
if (bindingResult.hasErrors()){
//获取异常信息对象
List<ObjectError> errors=bindingResult.getAllErrors();
//将异常信息输出
for (ObjectError error : errors){
System.out.println(error.getDefaultMessage());
}
}
System.out.println(info.getUser_email());
return "index";
}