【发布时间】:2012-01-04 05:36:52
【问题描述】:
我正在使用 spring mvc 3.0。这是我的控制器类:
@Controller
@RequestMapping("/author")
public class AuthorController {
@Autowired
private IAuthorDao authorDao;
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(
dateFormat, true));
}
@RequestMapping(method = RequestMethod.GET)
public String get(Model model) {
return "author-list";
}
@RequestMapping(value = "/new", method = RequestMethod.GET)
public String create(Model model) {
model.addAttribute("author", new Author());
return "author-form";
}
@RequestMapping(value = "/new", method = RequestMethod.POST)
public String createPost(@ModelAttribute("author") Author author,
BindingResult result) {
new AuthorValidator().validate(author, result);
if (result.hasErrors()) {
return "author-form";
} else {
authorDao.persist(author);
return "redirect:/author/" + author.getId();
}
}
@RequestMapping(value = "/{authorId}", method = RequestMethod.GET)
public String view(@PathVariable("authorId") int authorId) {
return "author-view";
}
}
我正在尝试验证作者对象。它具有类型为日期的 dob attr。
我正在使用以下类进行验证:
public class AuthorValidator {
public void validate(Author author, Errors errors) {
if(author.getfName()==null)
errors.rejectValue("fName", "required", "required");
else if (!StringUtils.hasLength(author.getfName())) {
errors.rejectValue("fName", "required", "required");
}
if(author.getfName()==null)
errors.rejectValue("lName", "required", "required");
else if (!StringUtils.hasLength(author.getlName())) {
errors.rejectValue("lName", "required", "required");
}
if(author.getDob()==null)
errors.rejectValue("dob", "required", "required");
else if (!StringUtils.hasLength(author.getDob().toString())) {
errors.rejectValue("dob", "required", "required");
}
}
}
当我没有在它提供所需消息的表单中输入任何内容时,它是正确的,但是当我提供不正确的格式时,它会将Failed to convert property value of type java.lang.String to required type java.util.Date for property dob; nested exception is java.lang.IllegalArgumentException: Could not parse date: Unparseable date: "asdads"
required 作为消息写入。如何使它像“无效日期”。
谢谢。
【问题讨论】:
标签: validation spring-mvc