data validation for SPRINGMVC
In the Web application, in order to prevent the data from the client to throw the program exception, often need to verify the data, input authentication is divided into client authentication and server-side authentication.
Client-side validation is primarily done through JavaScript scripts, while server-based validation is primarily validated by Java code
In order to ensure the security of the data, the client and server-side authentication are required in general.
In the first two we showed how to bind the data and how to ensure the correctness of the data we get when we bind the data? This is what we want to say in this article, data validation.
Here we use Hibernate-validator to verify, Hibernate-validator implements the JSR-303 validation framework to support annotation style validation. First we need to go to the http://hibernate.org/validator/to download the required jar package, here with 4.3.1.Final as the
The Hibernate-validator-4.3.1.final.jar, Jboss-logging-3.3.0.jar, Validation-api-1.0.0.ga.jar are added to the project after extracting the three packages.
Configuration steps:
Step one, the following configuration is first done in spring-servlet.xml, we use annotations to match
<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xmlns:p= "http://www.springframework.org/schema/p"Xmlns:mvc= "Http://www.springframework.org/schema/mvc"Xmlns:context= "Http://www.springframework.org/schema/context"xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans. XSD Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-conte Xt.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/MVC http://www.springframework.org/schema/mvc/spring-mvc.xsd " /c5>> <!--let spring scan all the classes under the package to make the classes annotated with spring take effect - <Context:component-scanBase-package= "Cn.yxj.controller"/> <!--Generate Authenticator - <BeanID= "Myvalidator"class= "Org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> < Propertyname= "Providerclass"value= "Org.hibernate.validator.HibernateValidator"></ Property> </Bean> <!--registering MVC annotation Drivers - <Mvc:annotation-drivenValidator= "Myvalidator"/> </Beans>
Step two, check the entity class needs to verify the configuration
PackageCn.yxj.pojo;Importjava.util.List;ImportJavax.validation.constraints.Max;Importjavax.validation.constraints.Min;ImportJavax.validation.constraints.Pattern;Importjavax.validation.constraints.Size;ImportOrg.hibernate.validator.constraints.NotEmpty; Public classUserInfo {@NotEmpty (message= "User name cannot be empty") @Size (min=3,max=6,message= "name length should be in {Min}-{max} characters") PrivateString username; @Min (Value=0,message= "score cannot be less than {value}") @Max (value=100,message= "score cannot be greater than {value}") PrivateInteger score; @NotEmpty (Message= "Cell phone number is not allowed to be empty") @Pattern (regexp= "^1[34578]\\d{9}$", message= "phone number format is incorrect") PrivateString Phone; PublicString GetUserName () {returnusername; } Public voidSetusername (String username) { This. Username =username; } PublicInteger Getscore () {returnscore; } Public voidSetScore (Integer score) { This. score =score; } PublicString Getphone () {returnphone; } Public voidSetphone (String phone) { This. Phone =phone; }}
Step three, in our processor class to do the appropriate judgment processing
Note: In our method parameters we need to add a @validated identifier to the entity we are verifying
PackageCn.yxj.controller;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.validation.BindingResult;ImportOrg.springframework.validation.FieldError;Importorg.springframework.validation.annotation.Validated;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.servlet.ModelAndView;Importcn.yxj.pojo.UserInfo; @Controller Public classmycontroller{//Processor Method@RequestMapping (value= "/list.do") PublicModelandview Dofirst (@Validated UserInfo info,bindingresult br) {modelandview mv=NewModelandview (); Mv.addobject ("Info", info); Mv.setviewname ("/list.jsp"); intErrorcount=Br.geterrorcount (); if(errorcount>0) {Fielderror nameerror=br.getfielderror ("username"); Fielderror Scoreerror=br.getfielderror ("Score"); Fielderror Phoneerror=br.getfielderror ("Phone"); if(nameerror!=NULL) {String nameerrormsg=Nameerror.getdefaultmessage (); Mv.addobject ("Nameerrormsg", nameerrormsg); } if(scoreerror!=NULL) {String scoreerrormsg=Scoreerror.getdefaultmessage (); Mv.addobject ("Scoreerrormsg", scoreerrormsg); } if(phoneerror!=NULL) {String phoneerrormsg=Phoneerror.getdefaultmessage (); Mv.addobject ("Phoneerrormsg", phoneerrormsg); } mv.setviewname ("/index.jsp"); } returnMV; } }
Step four, prepare the JSP page
<%@ Page Language="Java"Import="java.util.*"pageencoding="Utf-8"%><%StringPath=Request.getcontextpath ();StringBasePath=Request.getscheme ()+"://"+Request.getservername ()+":"+Request.getserverport ()+Path+"/";%><!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en"><HTML> <Head> <Basehref= "<%=basePath%>"> <title>Data validation</title> </Head> <Body> <formAction= "${pagecontext.request.contextpath}/list.do"Method= "POST"> <H1>Data validation</H1>Name:<inputname= "username"/>${NAMEERRORMSG}<BR/><BR/>Score:<inputname= "Score" />${SCOREERRORMSG}<BR/><BR/>Tel:<inputname= "Phone" />${PHONEERRORMSG}<BR/><BR/> <inputtype= "Submit"value= "Register"/> </form> </Body></HTML>
To complete this configuration
Data validation for SPRINGMVC