Spring MVC中的验证
问题内容:
如何获得验证器类中的请求对象,因为我需要验证内容,即请求对象中存在的参数。
问题答案:
不能100%确定我正确地遵循了您的问题,但是使用Spring MVC,您可以将对象传递到方法中并对其进行注释(至少在Spring 3中如此),如下所示:
@RequestMethod(value = "/accounts/new", method = RequestMethod.POST)
public String postAccount(@ModelAttribute @Valid Account account, BindingResult result) {
if (result.hasErrors()) {
return "accounts/accountForm";
}
accountDao.save(account);
}
这里的相关注释是@Valid,它是JSR-303的一部分。也包括BindingResult参数,因此您可以检查错误,如上所述。