问题描述
在 User 实体类的 userID 属性加 @NotEmpty 注解:
public class User{
@NotEmpty(message = "ID不能为空", groups = {RuleGroupA.class})
private String userID;
创建 Controller:
@Controller
public class GroupsValidationController {
@RequestMapping("/group1")
public String validGroupA(@Validated({RuleGroupA.class}) User user, BindingResult result){
System.out.println(result);
return "forward:/index.jsp";
}
}
请求带 userID 参数的 URL:
http://localhost:8080/springmvc/group1?userID=123
控制台却报 userID 为空:
org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'user' on field 'userID': rejected value [null]; codes [NotEmpty.user.userID,NotEmpty.userID,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.userID,userID]; arguments []; default message [userID]]; default message [ID不能为空]
原因分析
User 实体类的属性没有 getter/sette 方法,当然会取不到请求中的参数。
解决方案
User 实体类的属性加上 getter/sette 方法,再次请求,BindingResult 验证通过。
public class User{
@NotEmpty(message = "ID不能为空", groups = {RuleGroupA.class})
private String userID;
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
}
标签:String,NotEmpty,class,userID,public,报错,User,BindingResult
From: https://www.cnblogs.com/SergioEchigo/p/17056311.html