Spring MVC uses the features that Hibernate validator Framework can implement:
1. Annotate Java Bean Declaration validation rules.
2. Add a message error message source for internationalization configuration.
3. Display the error message with the errors tag in spring form.
Advantage:
The code is concise.
Realize:
1. Use Hibernate validator to introduce at least two jar packages:
Hibernate-validator-5.3.4.final.jar, Validation-api-1.1.0.final.jar
2. The annotations defined in the JSR specification are VALIDATION-API under Javax.validation.constraints package, please check it yourself.
3. Adding inspection rules using annotations in Java beans
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< C6/>return username; 9 }10 public void Setusername (String username) { this.username = username;12 }13}
Configuration of 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 @PostMapping (value = "/register") the Public String Register (@ Modelattribute ("user") @Valid UserInfo user, Errors Errors) { if (errors.haserrors ()) {] " register"; }16 return "Redirect:/index"; 25}
The corresponding register.jsp file:
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 Here are some things to note:
- The form label is submitted to the current request path by default if the Action property is not declared.
- @Valid annotation Specifies the object of the checksum, @ModelAttribute ("user") annotation declares the model object, and value needs to match the value of the CommandName property, or the <sf:errors> tag cannot find the corresponding object;
If the model object name is not declared, then the default is UserInfo (the first lowercase of the class name).
- The Errors object stores the error message, which needs to be immediately following the object @valid the annotation.
- The Get method accesses/register, displays rigister.jsp, and provides an object to the JSP, which corresponds to the value of the CommandName property in the form, and the JSP stores the form data in the object.
Post Submission Form, if there is an error message, the input tag that returns rigister.jsp,spring will fill in the previously entered object data, that is, the value of User.username, and <sf:errors> The tag gets the user.username error message from the Errors object (that is, the information specified by the message) and renders the <sf:errors> tag as a <span> tag (if interested, you can study the source code of the tag library).
4.spring-dispatcher-servlet.xml Configuring Hibernate validator, and configuring international resources
1 <mvc:annotation-driven validator= "Validator"/> 6 <mvc:default-servlet-handler/> 7 <bean Id= "RequestHandler" class= "org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" >14 <property name= "Usesuffixpatternmatch" value= "false"/><!--turn off automatic use. * Suffix-->15 </bean>16 <bean id= "Requestadapter" class= " Org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter ">20 <property name=" Synchronizeonsession "value=" true "/>21 </bean>248 <bean id=" hibernate_validator_messages "class=" Org.s Pringframework.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_mess AGE_ZH_CN ">utf-8</prop>57 </props>58 </property>59 </bean>60 <be An id= "validator" class= "Org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" >61 <prope Rty name= "Providerclass" value= "Org.hibernate.validator.HibernateValidator"/>62 <property name= "validationm Essagesource "ref=" Hibernate_validator_messages "/>63 </bean>
Places to be aware of in the configuration:
Localvalidatorfactorybean:validationmessagesource is injected by the Set method and then converted to the Messageinterpolator object, If you do not configure Validationmessagesource
Information source, the default source hibernatevalidations_xx_xx.properties is used, Under the Org.hibernate.validator package, the specific file used is determined by Locale.getdefaultlocale ().
- The information source configuration class provided in Reloadableresourcebundlemessagesource:spring, supports proerties and XML files, changes the configuration without restarting the service, basenames specifies the file location and name ( You can use the classpath prefix), fileencodings specifies how each file is encoded, and spring first finds the. properties suffix file, and then finds the. xml suffix file.
The 5.spring-dispatcher-servlet.xml is fully configured as follows:
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 http://www.springframework.org/schema/context/ Spring-context-4.3.xsd Http://www.springframework.org/schema/mvc Http://www.springframework.org/schema /mvc/spring-mvc-4.3.xsd "> <context:component-scan base-package=" Sps.controller "/>-<co Ntext:annotation-config/> Panax <mvc:annotation-driven validator= "Validator"/> Rvlet-handler/> <bean id= "reqUesthandler "class=" org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping "> &L T;property name= "Usesuffixpatternmatch" value= "false"/><!--turn off automatic use. * Suffix----</bean> D= "Requestadapter" class= "Org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" > <property name= "synchronizeonsession" value= "true"/> </bean> $68 <!-- Configure the View resolver for Dispatcherservlet----<bean id= "Internalresolver" class=. Web.servlet.view.InternalResourceViewResolver "> <property name=" prefix "value="/web-inf/views/"/> 73 <property name= "suffix" value= ". jsp"/> "<property name=" Viewclass "value=" org.springframework.we B.servlet.view.jstlview "/> <property name=" exposecontextbeansasattributes "value=" true "/>-</ bean> <bean id= "HiberNate_validator_messages "class=" Org.springframework.context.support.ReloadableResourceBundleMessageSource "> <property name= "Basenames" > 94 <list> <value>/web-inf/hibernat E_validator_messages/hibernate_validator_message_zh_cn</value> </list> </property > 98 <property name= "Fileencodings" > <props>100 <prop key=/web-i NF/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.beanva Lidation. Localvalidatorfactorybean ">105 <property name=" Providerclass "value=" Org.hibernate.validator.HibernateValid Ator "/>106 <property name=" Validationmessagesource "ref=" Hibernate_validator_messages "/>107 </bea N>108 109 </beans>
Places to be aware of in the configuration:
Viewclass in Internalresourceviewresolver is configured as Jstlview, and if you use the Spring tag library you must declare it as Jstlview, otherwise the spring tag library may not work or even cause an error.
Configuring the servlet in 6.web.xml will not be verbose.
Spring MVC uses Hibernate validator validation framework, internationalized configuration