先看看几个关键词 @Valid @Pattern @NotNull @NotBlank @Size BindingResult 这些就是Spring MVC的数据校验的几个注解。 那怎么用呢?往下看
1.先在pom.xml文件中加入依赖
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.3.0.Final</version> </dependency>
2.写controller层
@Controller @RequestMapping("/user") public class UserController extends BaseController{ @RequestMapping("/index") public String index() { return "index"; } @RequestMapping("/toAddUser") public String toAddUserPage() { return "addUser"; } /** * form表单添加用户,并用注解形式校验 * @Valid 表示 userModel要进行校验 * BindingResult 表示绑定校验的错误信息返回 * @param userModel * @param bindingResult * @return */ @RequestMapping("/add") public String addUser(@Valid @ModelAttribute("userModel") UserModel userModel, BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) { FieldError fieldError = bindingResult.getFieldError(); String validMess = fieldError.getDefaultMessage(); model.addAttribute("errors", validMess); return "error"; } System.out.println("用户姓名:" + userModel.getName()); System.out.println("用户邮箱:" + userModel.getEmail()); //用重定向防止页面刷新重复提交 return "redirect: /user/index"; } }
3、看看UserModel.java
public class UserModel { private Integer id; // @NotNull(message = "姓名不能为空") @NotBlank(message = "{username.not.empty}") // @Size(min = 3, max = 10, message = "please input right length") private String name; private Integer age; private String gender; @Pattern(regexp = "^[A-Za-z\\d]+([-_.][A-Za-z\\d]+)*@([A-Za-z\\d]+[-.])+[A-Za-z\\d]{2,4}$", message = "{username.not.empty}") private String email; @NotNull private String phone; setters... getters.... }
4、在spring 的配置文件中添加配置信息 applicationContext.xml
<!--JSR-303 @Valid 国际化支持配置 --> <mvc:annotation-driven validator="validator" conversion-service="conversion-service" /> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/> <!-- 如果不加默认到 使用classpath下的 ValidationMessages.properties --> <property name="validationMessageSource" ref="messageSource"/> </bean> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="classpath:valid-message-zh" /> <property name="fileEncodings" value="utf-8"/> <property name="cacheSeconds" value="120"/> </bean> <bean id="conversion-service" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />
5、别忘记配置文件中的 valid-message-zh.properties哦
username.not.empty=\u7528\u6237\u540d\u4e0d\u80fd\u4e3a\u7a7a
参考:
[1] 《Spring实战》,人民邮电出版社, Craig Walls