SpringMVC中整合JSR-303 验证表单输入
JSR-303是sun的基于注解的JavaBean校验规范,仅仅是一个规范,没有具体实现。Spring也没有对其进行实现,要想在SpringMVC中需要使用JSR-303就需要提供一个对JSR-303规范的实现,最常见的是Hibernate Validator。
1. pom依赖
<!-- JSR-303 -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<!-- Hibernate Valiadator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.1.Final</version>
</dependency>
2. 在${dispatcherServletName}-servlet.xml中配置,最简化为:
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
<!-- <property name="validationMessageSource" ref="messageSource" /> -->
</bean>
这里使用了各种默认的message,如需国际化等配置,
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:messages</value>
<value>classpath:org/hibernate/validator/ValidationMessages</value>
</list>
</property>
<property name="useCodeAsDefaultMessage" value="true" />
<property name="defaultEncoding" value="UTF-8" />
<property name="cacheSeconds" value="60" />
</bean>
3. 对应的POJO为
package example.entity;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
public class User {
@Pattern(regexp = "\\d+", message = "number only")
private String userId;
@Size(min = 3, max = 10, message = "User Name must be between 3 and 10 characters long")
private String userName;
//getters and setters
}
4. SpringMVC的controller层代码
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(Model model, @Valid User user, BindingResult bindingResult) throws InterruptedException, IOException {
if (bindingResult.hasErrors()) {
return "createUser";
}
userMap.put(user.getUserId(), user);
return "redirect:/user";
}
@Valid注解是JSR-303的一部分, 它表明参数在传入之前需要进行校验,否则,不予校验。
如果校验User出错的话,错误将会作为第二个参数以BindingResult的形式传递给create()方法。create()方法调用hasErrors()去做对应处理。