Spring MVC Data validation

Source: Internet
Author: User
Tags aop

In a Web application, it is often necessary to validate the data in order to prevent a program exception from being raised by the client. Input validation is divided into client-side authentication and server-end validation. 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.

1. Importing the JAR Package

SPRINGMVC supports the JSR (Java Specification Result,java specification proposal) 303-bean Validation Data validation specification. And the specification of the implementation of many, of which more commonly used is hibernate Validator. It is important to note that Hibernate validator is one of the hibernate products that are tied to hibernate orm. This can be seen from the form of resources available on the Hibernate website.

Hibernate-validator-4.3.1.final.jar, Jboss-logging-3.3.0.jar, Validation-api-1.0.0.ga.jar These three packages are added to the project

2. Configure the authenticator in the Applicationcontext.xml

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Xmlns:context= "Http://www.springframework.org/schema/context"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"Xmlns:tx= "Http://www.springframework.org/schema/tx"Xmlns:mvc= "Http://www.springframework.org/schema/mvc"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-context.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop.xsd/HTTP WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX http://www.springframework.org/schema/tx/spring-tx.xsd/HTTP Www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd ">        <!--Configuring the Package scanner -       <Context:component-scanBase-package= "Cn.controller"></Context:component-scan>              <!--Configuring Validators -       <BeanID= "Myvalidator"class= "Org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">           < Propertyname= "Providerclass"value= "Org.hibernate.validator.HibernateValidator"></ Property>       </Bean>               <Mvc:annotation-drivenValidator= "Myvalidator"/></Beans>

3. Defining entity classes, marking annotations

 Packagecn.entity;ImportJavax.validation.constraints.Max;Importjavax.validation.constraints.Min;ImportJavax.validation.constraints.Pattern;Importjavax.validation.constraints.Size;ImportOrg.hibernate.validator.constraints.NotEmpty;/** *  * @authorJingpeppe **/ Public classUserInfo {//must be between 0 and 100@Min (value=0,message= "score minimum is {value}") @Max (value=100,message= "score Max is {value}")    PrivateInteger score; //mobile phone number must not be empty, must be beginning with 1 second bit 3,4,5,6,7,8,9 last 9 bit random@NotEmpty (message= "mobile phone number is not allowed to be empty") @Pattern (regexp= "^1[3,4,5,6,7,8,9]\\d{9}$", message= "phone number is incorrect")  PrivateString Phone; //cannot be empty//must be 6 characters or more@NotEmpty (message= "User name cannot be empty") @Size (min=6,message= "Name of at least 6 characters")  PrivateString name;  PublicInteger Getscore () {returnscore; }     Public voidSetScore (Integer score) { This. score =score; }     PublicString Getphone () {returnphone; }     Public voidSetphone (String phone) { This. Phone =phone; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }    }

4. make the appropriate judgment in our processor class

 PackageCn.controller;ImportJavax.validation.Valid;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.validation.BindingResult;ImportOrg.springframework.validation.FieldError;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.servlet.ModelAndView;ImportCn.entity.UserInfo;/** *  * @authorJingpeppe **/@Controller Public classFirstcontroller {@RequestMapping ("/first.do")     PublicModelandview Dofirst (@Valid UserInfo info,bindingresult br) {modelandview mv=NewModelandview (); Mv.setviewname ("/welcome.jsp");        intErrorcount =Br.geterrorcount (); if(errorcount>0) {Fielderror score = br.getfielderror ("Score"); Fielderror name= Br.getfielderror ("name"); Fielderror Phone= Br.getfielderror ("Phone"); if(score!=NULL) {Mv.addobject ("Scoremsg", Score.getdefaultmessage ()); }                        if(name!=NULL) {Mv.addobject ("Namemsg", Name.getdefaultmessage ()); }                        if(phone!=NULL) {Mv.addobject ("Phonemsg", Phone.getdefaultmessage ()); } mv.setviewname ("/index.jsp"); }               returnMV; }}

index.jsp

<%@ Pagelanguage= "Java"Import= "java.util.*"pageencoding= "Utf-8"%><%stringPath= Request.getcontextpath ();String BasePath= Request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%><!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en"><HTML>  <Head>    <Basehref= "<%=basePath%>">        <title></title>    <Scripttype= "Text/javascript"src= "Js/jquery-1.8.3.js"></Script>     </Head>    <Body>    <H1>Data validation</H1>    <formAction= "${pagecontext.request.contextpath}/first.do"Method= "POST">Score:<inputname= "Score" /> <span>${SCOREMSG}</span><BR/><BR/>Name:<inputname= "Name"/><span>${NAMEMSG}</span><BR/><BR/>Tel:<inputname= "Phone"/><span>${PHONEMSG}</span><BR/><BR/>       <inputtype= "Submit"value= "Register"/>    </form>  </Body></HTML>

Effect

(welcome.jsp) page when successful

Alert when wrong

Spring MVC Data validation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.