我需要帮助。当用户忘记输入birthDate时,如何在日期字段留空时捕获异常。我使用Validator接口来处理它。我希望Java在birthdate字段为空时在浏览器上打印消息FootballPlayer birth date is required.
当生日期字段为空时,它会打印出Exception和我创建的错误消息。它的打印方式如下:
无法将类型为java.lang.String的属性值转换为属性birthDate的必需类型java.util.Date;嵌套异常是java.lang.IllegalStateException:无法将类型[java.lang.String]的值转换为属性birthDate所需的类型[java.util.Date]:找不到匹配的编辑器或转换策略
FootballPlayer出生日期是必需的。
我只想打印FootballPlayer birth date is required.
。我怎样才能做到这一点?
我是java和编程的新手。请帮忙。
FootballPlayerValidator.java:
if (footballPlayer.getBirthDate() == null || footballPlayer.getBirthDate().equals(null)) {
try {
errors.rejectValue("birthDate", null, null, "FootballPlayer birth date is required.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
FootballPlayerController.java:
@RequestMapping (value = "/add", method = RequestMethod.POST)
public String saveFootballPlayer (@ModelAttribute ("footballPlayer") FootballPlayer footballPlayer,
BindingResult result, Model model, HttpSession session) {
System.out.println("Saving footballPlayer");
footballPlayerValidator.validate(footballPlayer, result);
if (result.hasErrors())
return "addFootballPlayer";
saveFootballPlayer(footballPlayer);
return "successfullySaved";
}
在我的setter和getter中,我将birthdate声明为Date,也在我的数据库中。
FootballPlayer.java:
private Date birthDate;
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}