当我输入字段“Age”(这是一个整数)时,除了数字之外的任何数据都会发生错误。我只需要显示验证器的错误消息。
我的模特:
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue
private Integer id;
private String name;
private Integer age;
private Boolean isAdmin;
@GeneratedValue
private Timestamp createdDate;
验证
public class FormValidator implements Validator {
private Pattern pattern;
private Matcher matcher;
@Override
public boolean supports(Class<?> aClass) {
return true;
}
@Override
public void validate(Object o, Errors errors) {
User user = (User) o;
ValidationUtils.rejectIfEmptyOrWhitespace(errors,"name", "Mess1", "Mess2");
if(!(user.getName()!= null && user.getName().isEmpty())) {
pattern = Pattern.compile("[a-zA-Z]+");
matcher = pattern.matcher(user.getName());
if (!matcher.matches()) {
errors.rejectValue("name", "name contains non char", "enter a valid name");
}
if (user.getAge() != null) {
pattern = Pattern.compile("[0-9]{0,3}");
matcher = pattern.matcher(user.getAge().toString());
if (!matcher.matches()) {
errors.rejectValue("age", "mess1", "mess2");
}
if (user.getAge().toString().length() > 3) {
errors.rejectValue("age", "age to big", "not more 3 int");
}
}
}
}
}
控制器:
@RequestMapping(value="/add", method=RequestMethod.POST)
public ModelAndView addingUser(@ModelAttribute User user, BindingResult result) {
FormValidator formValidator = new FormValidator();
formValidator.validate(user,result);
if(result.hasErrors()){
ModelAndView modelAndView = new ModelAndView("add-user-form",result.getModel());
return modelAndView;
}
ModelAndView modelAndView = new ModelAndView("home");
userService.addUser(user);
String message = "User was successfully added.";
modelAndView.addObject("message", message);
return modelAndView;
}
据我所知,错误源于页面从已完成的表单中收到旧的错误对象,字段为“age”(其中,数字以外的数据)。
但是如果我分别发送一个新对象和BindingResult形式,则不显示错误。 像这样:
if(result.hasErrors()){
ModelAndView modelAndView = new ModelAndView("add-user-form");
modelAndView.addObject("user,new User()");
modelAndView.addObject("errors",result);
return modelAndView;
}
如何将BindingResult与坏对象分开发送,或者如何避免这种情况?
答案 0 :(得分:0)
如果createUser()方法返回false,请尝试将错误设置为结果对象,如下面的代码。
boolean IsUserCreated = userDAO.createUser(user);
if(isUserCreated == true) {
} else {
result.addError(new objectError("emailAddress", "Email ID is already in use")); // here result is BindingResult, emailAddress is the name of the input field in the form.
modelMap.put("errors", result.getAllErrors());
}