在Spring MVC中验证

Dar*_*n.R 5 java validation spring spring-mvc

如何在验证器类中获取请求对象,因为我需要验证内容,即请求对象中存在的参数.

Ral*_*lph 9

你有两个选择:

  • JSR 303(Bean Validation)验证器
  • Spring Validators

对于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/>
Run Code Online (Sandbox Code Playgroud)

对于Spring Validators,您需要编写实现org.springframework.validation.Validator接口的Validator(请参阅Jigar Joshi的答案).您必须在Controller中注册Validator.在Spring 3.0,你可以在做注解的方法,通过使用WebDataBinder(setValidator将是父类的方法)@InitBinder.setValidatorDataBinder

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) { ... }
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅Spring参考,第5.7.4节Spring MVC 3验证.

顺便说一句:在Spring 2中,有一些像setValidatorSimpleFormController中的属性.


小智 1

不能 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);
}
Run Code Online (Sandbox Code Playgroud)

这里相关的注释是@Valid,它是JSR-303的一部分。还包括 BindingResult 参数,以便您可以检查错误,如上所示。