[英]Validation in Spring MVC
如何在驗證器類中獲取請求對象,因為我需要驗證內容,即請求對象中存在的參數。
你有兩個選擇:
對於JSR 303,您需要Spring 3.0並且必須使用JSR 303 Annotations注釋您的Model類,並在Web Controller Handler方法中在您的參數前面編寫@Valid。 (就像Willie Wheeler在他的回答中所示 )。 另外,您必須在配置中啟用此功能:
<!-- JSR-303 support will be detected on classpath and enabled automatically -->
<mvc:annotation-driven/>
對於Spring Validators ,您需要編寫實現org.springframework.validation.Validator接口的Validator(請參閱Jigar Joshi的答案 )。 您必須在Controller中注冊Validator。 在Spring 3.0,你可以在做這個@InitBinder
注解的方法,通過使用WebDataBinder .setValidator
( setValidator將是父類的方法DataBinder
)
Example (from the spring docu)
@Controller
public class MyController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new FooValidator());
}
@RequestMapping("/foo", method=RequestMethod.POST)
public void processFoo(@Valid Foo foo) { ... }
}
有關更多詳細信息,請參閱Spring參考,第5.7.4節Spring MVC 3驗證 。
BTW:在Spring 2有像成才setValidator
在SimpleFormController財產。
使用簡單的驗證器(您的自定義驗證器)您不需要請求對象來在Validator中獲取參數。 你可以直接從中獲得它。
例如:這將檢查來自請求的字段name
和age
public class PersonValidator implements Validator {
/**
* This Validator validates just Person instances
*/
public boolean supports(Class clazz) {
return Person.class.equals(clazz);
}
public void validate(Object obj, Errors e) {
ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
Person p = (Person) obj;
if (p.getAge() < 0) {
e.rejectValue("age", "negativevalue");
} else if (p.getAge() > 110) {
e.rejectValue("age", "too.darn.old");
}
}
}
另見
不是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參數,以便您可以檢查錯誤,如上所示。
您可以使用HttpServletRequest參數輕松添加另一個方法。
public void validateReq(Object target, Errors errors,HttpServletRequest request) {
// do your validation here
}
請注意,您沒有在此處覆蓋方法
當我使用spring驗證器驗證驗證碼時,我也有同樣的問題。 在驗證器實現器中,我想從HttpSession獲取正確的驗證碼(來自HttpServletRequest獲取HttpSession)。
沒有找到任何好的代碼,以獲得驗證器,所以很糟糕!
有一些折衷方案如下:
在綁定表單DTO中添加一個附加字段(調用:correctCaptcha),在Controller方法中設置HttpSession的字段值,然后就可以在驗證器中驗證
public class UserRegisterDto { private String correctCaptcha; //getter,setter }
在綁定表單DTO中添加HttpServletRequest引用,然后可以在驗證器中使用它。
public class UserRegisterDto { private HttpServletRequest request; //getter ,setter } @RequestMapping(value = "register.hb", method = RequestMethod.POST) public String submitRegister(@ModelAttribute("formDto") @Valid UserRegisterDto formDto, HttpServletRequest request,BindingResult result) { formDto.setRequest(request); if (result.hasErrors()) { return "user_register"; } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.