spring mvc使用hibernate validator框架能夠實現的功能:html
1. 註解java bean聲明校驗規則。java
2. 添加message錯誤信息源實現國際化配置。web
3. 結合spring form中的errors標籤展示錯誤信息。spring
優點:api
代碼簡潔。spring-mvc
實現:mvc
1. 使用hibernate validator 至少要引入兩個jar包:app
hibernate-validator-5.3.4.Final.jar , validation-api-1.1.0.Final.jar框架
2. JSR規範定義的註解在validation-api下javax.validation.constraints包下,請自行查看。jsp
3. java bean中使用註解添加檢驗規則
1 public class UserInfo { 2 3 @Size(min = 8,max = 20,message="{username.size}") 4 @Pattern(regexp="[_a-zA-Z0-9]+",message="{username.pattern}") 5 private String username; 6 7 public String getUsername() { 8 return username; 9 } 10 public void setUsername(String username) { 11 this.username = username; 12 } 13 }
Controller的配置
1 @Controller
3 public class UserController { 5 @GetMapping(value = "/register") 6 public String showRegister(Model model){ 7 model.addAttribute("user",new UserInfo()); 8 return "register"; 9 } 10 11 @PostMapping(value = "/register") 12 public String register(@ModelAttribute("user") @Valid UserInfo user, Errors errors) { 13 if (errors.hasErrors()) { 14 return "register"; 15 } 16 return "redirect:/index"; 17 } 25 }
對應的register.jsp文件:
1 <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> 3 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 4 <%@taglib uri="http://www.springframework.org/tags/form" prefix="sf"%> 5 <html> 6 <head> 10 <title></title> 26 </head> 27 <body> 84 <sf:form method="POST" commandName="user"> 85 <sf:input path="username"/> 86 <sf:errors path="username"/><br> 88 <sf:password path="password"/> 89 <sf:errors path="password"/><br> 91 <sf:password path="re_password"/> 92 <sf:errors path="re_password" /><br> 94 <sf:input path="email" type="email"/> 95 <sf:errors path="email" /><br> 97 <sf:input path="phone"/> 98 <sf:errors path="phone" /><br> 100 <input type="submit" value="註冊"> 101 </sf:form> 106 </body> 107 </html>
其中須要注意的地方:
若是不聲明模型對象名稱,那麼默認是userInfo(即類名第一個首字母小寫).
post提交表單,若是有錯誤信息,返回rigister.jsp,spring的輸入標籤會填入以前輸入的對象數據,即user.username的值,而且<sf:errors>標籤會從Errors對象中獲取user.username錯誤信息(即message指定的信息),將<sf:errors>標籤渲染爲<span>標籤(有興趣的話能夠研究一下標籤庫的源碼)。
4.spring-dispatcher-servlet.xml配置hibernate validator,而且配置國際化資源
1 <mvc:annotation-driven validator="validator"/> 6 <mvc:default-servlet-handler /> 7 13 <bean id="requestHandler" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"> 14 <property name="useSuffixPatternMatch" value="false"/><!--關閉自動使用 .* 後綴--> 15 </bean> 16 <bean id="requestAdapter" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> 20 <property name="synchronizeOnSession" value="true"/> 21 </bean> 2 48 <bean id="hibernate_validator_messages" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> 49 <property name="basenames"> 50 <list> 51 <value>/WEB-INF/hibernate_validator_messages/hibernate_validator_message_zh_CN</value> 52 </list> 53 </property> 54 <property name="fileEncodings"> 55 <props> 56 <prop key="/WEB-INF/hibernate_validator_messages/hibernate_validator_message_zh_CN">UTF-8</prop> 57 </props> 58 </property> 59 </bean> 60 <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> 61 <property name="providerClass" value="org.hibernate.validator.HibernateValidator" /> 62 <property name="validationMessageSource" ref="hibernate_validator_messages"/> 63 </bean>
配置中須要注意的地方:
LocalValidatorFactoryBean :validationMessageSource經過set方法注入,而後轉換爲MessageInterpolator對象,若是不配置validationMessageSource
信息源,那麼會使用默認的信息源HibernateValidations_xx_xx.properties,位於org.hibernate.validator包下,具體使用哪一個文件由Locale.getDefaultLocale()決定。
5.spring-dispatcher-servlet.xml完整配置以下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <beans xmlns="http://www.springframework.org/schema/beans" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xmlns:mvc="http://www.springframework.org/schema/mvc" 7 xsi:schemaLocation=" 8 http://www.springframework.org/schema/beans 9 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 10 http://www.springframework.org/schema/context 11 http://www.springframework.org/schema/context/spring-context-4.3.xsd 12 http://www.springframework.org/schema/mvc 13 http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 14 "> 22 <context:component-scan base-package="sps.controller"/> 36 <context:annotation-config/> 37 45 <mvc:annotation-driven validator="validator"/> 49 50 <mvc:default-servlet-handler /> 57 <bean id="requestHandler" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"> 58 <property name="useSuffixPatternMatch" value="false"/><!--關閉自動使用 .* 後綴--> 59 </bean> 60 <bean id="requestAdapter" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> 64 <property name="synchronizeOnSession" value="true"/> 65 </bean> 66 67 <!-- 68 配置DispatcherServlet的視圖解析器 69 --> 70 <bean id="internalresolver" 71 class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 72 <property name="prefix" value="/WEB-INF/views/"/> 73 <property name="suffix" value=".jsp"/> 74 <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> 75 <property name="exposeContextBeansAsAttributes" value="true"/> 76 </bean> 77 92 <bean id="hibernate_validator_messages" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> 93 <property name="basenames"> 94 <list> 95 <value>/WEB-INF/hibernate_validator_messages/hibernate_validator_message_zh_CN</value> 96 </list> 97 </property> 98 <property name="fileEncodings"> 99 <props> 100 <prop key="/WEB-INF/hibernate_validator_messages/hibernate_validator_message_zh_CN">UTF-8</prop> 101 </props> 102 </property> 103 </bean> 104 <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> 105 <property name="providerClass" value="org.hibernate.validator.HibernateValidator" /> 106 <property name="validationMessageSource" ref="hibernate_validator_messages"/> 107 </bean> 108 109 </beans>
配置中須要注意的地方:
InternalResourceViewResolver 中的 viewClass 配置爲JstlView,若是使用spring 標籤庫的話必須 聲明爲 JstlView,否則spring標籤庫可能不起做用,甚至引發錯誤。
6.web.xml 中配置servlet就不羅嗦了。