SPRINGMVC Learning Series (6) Data validation

Source: Internet
Author: User
Tags wrappers jboss

Http://www.cnblogs.com/liukemng/p/3738055.html

In the series (4), (5) We show 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 want to go to http://hibernate.org/validator/download the required jar package, here to 4.3.1.Final as a demonstration, unzip the Hibernate-validator-4.3.1.final.jar, Jboss-logging-3.1.0.jar, Validation-api-1.0.0.ga.jar These three packages are added to the project.

Configure the Springservlet-config.xml file in the previous project as follows:

<!--default annotation map Support--<mvc:annotation-driven validator= "validator" conversion-service= "Conversion-service"/&        Gt <bean id= "Validator" class= "Org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" > < Property Name= "Providerclass" value= "Org.hibernate.validator.HibernateValidator"/> <!--not set defaults to Va under Classpath    Lidationmessages.properties--<property name= "Validationmessagesource" ref= "Validatemessagesource"/> </bean> <bean id= "Conversion-service" class= " Org.springframework.format.support.FormattingConversionServiceFactoryBean "/> <bean id=" Validatemessagesource "class=" Org.springframework.context.support.ReloadableResourceBundleMessageSource "> &lt ;p roperty name= "basename" value= "classpath:validatemessages"/> <property name= "fileencodings" value= "Utf-8" /> <property name= "cacheseconds" value= "</bean>"/>

where <property name= "basename" value= "Classpath:validatemessages"/> in classpath: Validatemessages to verify the file where the message is located, we need to add it under the Resources folder.

Add a Validatecontroller.java content to the Com.demo.web.controllers package as follows:

Package Com.demo.web.controllers;import Java.security.nosuchalgorithmexception;import Javax.validation.Valid; Import Org.springframework.stereotype.controller;import Org.springframework.ui.model;import Org.springframework.validation.bindingresult;import Org.springframework.web.bind.annotation.ModelAttribute; Import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestmethod;import com.demo.web.models.validatemodel;@ Controller@requestmapping (value = "/validate") public class Validatecontroller {@RequestMapping (value= "/test", meth            od = {requestmethod.get}) public String test (model model) {if (!model.containsattribute ("Contentmodel")) {        Model.addattribute ("Contentmodel", New Validatemodel ());    } return "Validatetest"; } @RequestMapping (value= "/test", method = {requestmethod.post}) public String test (model, @Valid @ModelAtt Ribute ("Contentmodel") Validatemodel Validatemodel, BindinGresult result) throws nosuchalgorithmexception{//If a validation error is returned to the form page if (Result.haserrors ())        return test (model);         return "Validatesuccess"; }    }

where @valid @ModelAttribute ("Contentmodel") Validatemodel Validatemodel @valid means to bind data to @modelattribute (" Contentmodel ") is verified.

Add a Validatemodel.java content to the Com.demo.web.models package as follows:

Package Com.demo.web.models;import Org.hibernate.validator.constraints.email;import Org.hibernate.validator.constraints.notempty;import Org.hibernate.validator.constraints.range;public Class validatemodel{        @NotEmpty (message= "{name.not.empty}")    private String name;    @Range (min=0, max=150,message= "{age.not.inrange}")    private String age;    @NotEmpty (message= "{email.not.empty}")    @Email (message= "{email.not.correct}")    private String email;        public void SetName (String name) {        this.name=name;    }    public void Setage (String age) {        this.age=age;    }    public void Setemail (String email) {        this.email=email;    }        Public String GetName () {        return this.name;    }    Public String Getage () {        return this.age;    }    Public String Getemail () {        return this.email;    }    }

Add the following in the file that contains the annotation validation message, the Validatemessages.properties file:

Name.not.empty=\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a\u3002age.not.inrange=\u5e74\u9f84\u8d85\u51fa\u8303\u56f4\ U3002email.not.correct=\u90ae\u7bb1\u5730\u5740\u4e0d\u6b63\u786e\u3002email.not.empty=\u7535\u5b50\u90ae\ u4ef6\u4e0d\u80fd\u60df\u6050\u3002

where Name.not.empty, respectively, corresponding to the Validatemodel.java file message= "xxx" in the xxx name, the following is the input in Chinese is automatically converted ASCII encoding, of course, you can also directly put XXX as a hint of content, Instead of adding another validatemessages.properties file, it's not the right thing to do, because there's no way to internationalize that hard-coded word.

In the Views folder, add validatetest.jsp and validatesuccess.jsp Two view, the contents are as follows:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" ><%@ taglib prefix= "Form" uri= "Http://www.springframework.org/tags/form"%>

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "    pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

One particular point to note is the method= of <form:form modelattribute= "Contentmodel" Modelattribute "post" in the validatetest.jsp View > The name xxx after = "xxx" must match the xxx name in the corresponding @valid @ModelAttribute ("xxx") , otherwise the model data and error information are not bound.

<form:errors path= "name" ></form:errors> displays the error message for the model's corresponding property, which displays the error information for all properties of the model when path= "*".

To run the test:

Click Submit directly:

You can see the error message that the setting is displayed correctly.

Fill in the Error data submission:

You can see the error message that the setting is still displayed correctly.

Fill in the correct data submission:

You can see that the validation was successful.

The following are the main validation notes and explanations:

Annotations

Applicable data types

Description

@AssertFalse

Boolean, Boolean

Verify that the element value of the annotation is false

@AssertTrue

Boolean, Boolean

Verify that the element value of the annotation is true

@DecimalMax (value=x)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive. Additionally supported by Hv:any sub-type of number andcharsequence.

Verifies that the element value of the annotation is less than or equal to the value specified by @ Decimalmax

@DecimalMin (value=x)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive. Additionally supported by Hv:any sub-type of number andcharsequence.

Verifies that the element value of the annotation is less than or equal to the value specified by @ decimalmin

@Digits (integer= integer digits, fraction= decimal place)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive. Additionally supported by Hv:any sub-type of number andcharsequence.

To verify the integer and maximum number of decimal digits for the element value of the annotation

@Future

Java.util.Date, Java.util.Calendar; Additionally supported by HV, if Thejoda time date/time API are on the class Path:any implementations Ofreadablepartia L andreadableinstant.

Verify that the annotation's element value (date type) is later than the current time

@Max (value=x)

BigDecimal, BigInteger, Byte, Short,int, long and the respective wrappers of the primitive types. Additionally supported by Hv:any sub-type ofcharsequence (the numeric value represented by the character sequence is eval uated), any sub-type of number.

Verifies that the element value of the annotation is less than or equal to the value specified by @max

@Min (value=x)

BigDecimal, BigInteger, Byte, Short,int, long and the respective wrappers of the primitive types. Additionally supported by Hv:any sub-type of charsequence (the numeric value represented by the char sequence is evaluate d), any sub-type of number.

Verifies that the element value of the annotation is greater than or equal to the value specified by @min

@NotNull

Any type

Verify that the element value of the annotation is not null

@Null

Any type

Verify that the element value of the annotation is null

@Past

Java.util.Date, Java.util.Calendar; Additionally supported by HV, if Thejoda time date/time API are on the class Path:any implementations Ofreadablepartia L andreadableinstant.

Verify that the annotation's element value (date type) is earlier than the current time

@Pattern (regex= Regular expression, flag=)

String. Additionally supported by Hv:any sub-type of Charsequence.

Validates that the element value of the annotation matches the specified regular expression

@Size (min= min, max= max)

String, Collection, Map and arrays. Additionally supported by Hv:any sub-type of Charsequence.

Verifies that the element value of the annotation is within a specified interval of min and max (inclusive), such as character length, collection size

@Valid

Any non-primitive type (reference type)

Validates the associated object, such as an order object in the account object, specifying the validation order object

@NotEmpty

CharSequence,CollectionMap and Arrays

Verifies that the element value of the annotation is not null and is not empty (string length is not 0, collection size is not 0)

@Range (min= min, max= max)

CharSequence, Collection, Map and Arrays,BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types

Verifies that the element value of the annotation is between the minimum and maximum values

@NotBlank

CharSequence

Verifies that the element value of the annotation is not null (NOT NULL, the first space is removed after the length is 0), differs from @notempty, @NotBlank is applied only to strings and the whitespace is stripped of the string when compared

@Length (min= lower limit, max= upper limit)

CharSequence

Validates the element value length of annotations within min and Max intervals

@Email

CharSequence

Verify that the element value of the annotation is email, or you can specify a custom email format via regular expressions and flag

For more information, please refer to the official documentation: http://docs.jboss.org/hibernate/validator/4.3/reference/en-US/html/validator-usingvalidator.html

The content of the data validation ends here, code download: Http://pan.baidu.com/s/1pJDc12V

SPRINGMVC Learning Series (6) 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.