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
@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方法
@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"; }