springMvc入门配置Validation

参考spring-framework-reference.pdf
8.8 Spring Validation小节
21.16 Configuring Spring MVC的Validation小节
http://hibernate.org/validator/documentation/

1.pom.xml添加以下依赖

        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>2.2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.2.2.Final</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.el</artifactId>
            <version>2.2.6</version>
        </dependency>
2.配置Bean
a.在AppConfig.java的RootApplicationContext配置一个Validator
    @Bean
    public LocalValidatorFactoryBean validator(){
        return new LocalValidatorFactoryBean();
    }
b.在继承WebMvcConfigurerAdapter的MvcConfig,重写getValidator方法
    @Autowired
    private Validator validator;
    @Override
    public Validator getValidator() {
        return validator;
    }
如果考虑只在web层做校验,也可以直接在WebApplicationContext声明Validator Bean,然后直接使用此Bean,同样也重写getValidator方法
3.使用:
a.声明约束,比如User有一个字段username.
    @NotNull
    @Size(min = 6, max = 14 ,message = "The username '${validatedValue}' must be between {min} and {max} characters long")
    private String username;
b.在Controller的方法参数做校验.
    @RequestMapping("/")
    public String index(Model model,@Valid User user,BindingResult br){
        if (br.hasErrors()){
            for (ObjectError objectError : br.getAllErrors()) {
                System.out.println("objectError = " + objectError);
            }
        }
        List<String> list= Arrays.asList("list1","list2","list3");
        model.addAttribute("list",list);
        return "user/index";
    }


你可能感兴趣的:(spring,mvc,validation)