Home >Java >javaTutorial >SpringMVC Learning Series (6) Data Verification

SpringMVC Learning Series (6) Data Verification

黄舟
黄舟Original
2017-03-03 10:58:111348browse

In series (SpringMVC Learning Series (6) Data Verification) and (SpringMVC Learning Series (6) Data Verification) we showed how to bind data. After binding the data, how to ensure the correctness of the data we get? This is what we are going to talk about in this article —> Data validation.

Here we use Hibernate-validator for verification. Hibernate-validator implements the JSR-SpringMVC Learning Series (6) Data Verification0SpringMVC Learning Series (6) Data Verification verification framework and supports annotation-style verification. First we have to go to http://www.php.cn/ to download the required jar package. Here we use SpringMVC Learning Series (6) Data Verification.SpringMVC Learning Series (6) Data Verification.SpringMVC Learning Series (6) Data Verification.Final as a demonstration. After decompression, hibernate-validator-SpringMVC Learning Series (6) Data Verification.SpringMVC Learning Series (6) Data Verification.SpringMVC Learning Series (6) Data Verification.Final.jar and jboss-logging-SpringMVC Learning Series (6) Data Verification.SpringMVC Learning Series (6) Data Verification The three packages .0.jar and validation-api-SpringMVC Learning Series (6) Data Verification.0.0.GA.jar are added to the project.

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

<!-- 默认的注解映射的支持 -->  
    <annotation-driven></annotation-driven>
    
    <bean>
        <property></property>
        <!--不设置则默认为classpath下的 ValidationMessages.properties -->
        <property></property>
    </bean>
    <bean></bean>
    <bean>  
        <property></property>  
        <property></property>  
        <property learning series data verificationspringmvc verification0></property>  
    </bean>


whereproperty name="basename" value="classpath:validatemessages"/> in classpath:validatemessagesFor the file where the annotation verification message is located, we need to add it in the resources folder.

Add a ValidateController.java in the com.demo.web.controllers package with the following content:

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", method = {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 model, @Valid @ModelAttribute("contentModel") ValidateModel validateModel, BindingResult result) throws NoSuchAlgorithmException{        
        //如果有验证错误 返回到form页面
        if(result.hasErrors())            return test(model);        return "validatesuccess";     
    }
    
}


Among them @Valid @ModelAttribute("contentModel") ValidateModel validateModel's @Valid means to validate after binding the data to @ModelAttribute("contentModel").

Add a ValidateModel.java in the com.demo.web.models package with the following content:

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=SpringMVC Learning Series (6) Data VerificationSpringMVC Learning Series (6) Data Verification0,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;
    }
    
}


Annotate the file where the verification message is located, which is validatemessages. Add the following content to the properties file:

name.not.empty=\uSpringMVC Learning Series (6) Data VerificationSpringMVC Learning Series (6) Data Verification0D\u79F0\uSpringMVC Learning Series (6) Data VerificationE0D\u80FD\uSpringMVC Learning Series (6) Data VerificationESpringMVC Learning Series (6) Data VerificationA\u7A7A\uSpringMVC Learning Series (6) Data Verification00SpringMVC Learning Series (6) Data Verification
age.not.inrange=\uSpringMVC Learning Series (6) Data VerificationE7SpringMVC Learning Series (6) Data Verification\u9F8SpringMVC Learning Series (6) Data Verification\u8D8SpringMVC Learning Series (6) Data Verification\uSpringMVC Learning Series (6) Data VerificationSpringMVC Learning Series (6) Data VerificationFA\u8SpringMVC Learning Series (6) Data Verification0SpringMVC Learning Series (6) Data Verification\uSpringMVC Learning Series (6) Data Verification6FSpringMVC Learning Series (6) Data Verification\uSpringMVC Learning Series (6) Data Verification00SpringMVC Learning Series (6) Data Verification
email.not.correct=\u90AE\u7BBSpringMVC Learning Series (6) Data Verification\uSpringMVC Learning Series (6) Data Verification7SpringMVC Learning Series (6) Data Verification0\uSpringMVC Learning Series (6) Data Verification7SpringMVC Learning Series (6) Data Verification0\uSpringMVC Learning Series (6) Data VerificationE0D\u6B6SpringMVC Learning Series (6) Data Verification\u786E\uSpringMVC Learning Series (6) Data Verification00SpringMVC Learning Series (6) Data Verification
email.not.empty=\u7SpringMVC Learning Series (6) Data VerificationSpringMVC Learning Series (6) Data VerificationSpringMVC Learning Series (6) Data Verification\uSpringMVC Learning Series (6) Data VerificationBSpringMVC Learning Series (6) Data Verification0\u90AE\uSpringMVC Learning Series (6) Data VerificationEF6\uSpringMVC Learning Series (6) Data VerificationE0D\u80FD\u60DF\u60SpringMVC Learning Series (6) Data Verification0\uSpringMVC Learning Series (6) Data Verification00SpringMVC Learning Series (6) Data Verification


name.not.empty, etc. respectively correspond to the xxx name in message="xxx" in the ValidateModel.java file, and the following The content is the ASCII code that is automatically converted when inputting Chinese. Of course, you can also write xxx directly as the prompt content without creating another validatemessages.properties file and adding it, but this is incorrect because if it is hard-coded, there will be no The method has been internationalized.

Add two views, validatetest.jsp and validatesuccess.jsp, in the views folder. The contents are as follows:

nbsp;html PUBLIC "-//WSpringMVC Learning Series (6) Data VerificationC//DTD HTML SpringMVC Learning Series (6) Data Verification.0SpringMVC Learning Series (6) Data Verification Transitional//EN" "http://www.wSpringMVC Learning Series (6) Data Verification.org/TR/htmlSpringMVC Learning Series (6) Data Verification/loose.dtd"><meta><title>Insert title here</title>
    <form>     
        
        <errors></errors><br><br>
            
        name:<input><br>
        <errors></errors><br>
        
        age:<input><br>
        <errors></errors><br>
        
        email:<input><br>
        <errors></errors><br>

        <input>
        
    </form>  


nbsp;html PUBLIC "-//WSpringMVC Learning Series (6) Data VerificationC//DTD HTML SpringMVC Learning Series (6) Data Verification.0SpringMVC Learning Series (6) Data Verification Transitional//EN" "http://www.wSpringMVC Learning Series (6) Data Verification.org/TR/htmlSpringMVC Learning Series (6) Data Verification/loose.dtd"><meta><title>Insert title here</title>
    验证成功!


It is particularly important to point out that in the validatetest.jsp view, form:form modelAttribute="contentModel" method="post">#modelAttribute="xxx"The name xxx following must be the same as Corresponding @Valid @ModelAttribute("xxx") The xxx names in are consistent, otherwise the model data and error information will not be bound.

form:errors path="name">form:errors>The error message corresponding to the attribute of the model will be displayed. When path="*", the error message of all attributes of the model will be displayed. error message.

Run the test:

SpringMVC Learning Series (6) Data Verification

## Click submit directly:

SpringMVC Learning Series (6) Data Verification

##You can see The error message for the setting is displayed correctly.

Fill in incorrect data and submit:

SpringMVC Learning Series (6) Data Verification

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

Fill in the correct data and submit:

SpringMVC Learning Series (6) Data Verification

SpringMVC Learning Series (6) Data Verification

##You can see that the verification is successful.

The following are the main verification annotations and instructions:

##Annotations@AssertFalse##BigDecimal, BigInteger, String, byte, short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.Verify that the annotated element value is less than or equal to the value specified by @DecimalMinBigDecimal, BigInteger, String, byte, short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.Verify the element value of the annotation The upper limit of the number of integers and decimal places##@Future@Max(value=x)@Min(value=x)@Pattern(regex=regular expression, flag=)@Size(min=minimum value, max=maximum value)@Valid##@NotEmptyCollectionVerify that the element value of the annotation is not empty (not null, and the length is 0 after removing the first space). Unlike @NotEmpty, @NotBlank only applies to strings and will remove spaces from the strings during comparison Verify that the element value length of the annotation is within the min and max intervals##@EmailCharSequence

For more information, please refer to the official documentation: http://docs.jboss.org/hibernate/validator/SpringMVC Learning Series (6) Data Verification.SpringMVC Learning Series (6) Data Verification/reference/en-US/html/validator-usingvalidator.html

Note: I didn’t pay attention to the sample code in the first SpringMVC Learning Series (6) Data VerificationSpringMVC Learning Series (6) Data Verification articles before. I don’t know why the package and uploaded at that time did not have a .project project file. As a result, after downloading, it could not be directly imported into eclipse to run the virtual machine. I deleted it again. These sample codes are not backed up, but the code files are still there, so you can create a new Dynamic Web Project and import the corresponding configuration files, controllers and views. Sorry for the inconvenience caused to everyone. Feel sorry.

The above is the content of data verification in the SpringMVC Learning Series (6). For more related content, please pay attention to the PHP Chinese website (www. php.cn)!


Applicable data types

Description

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 types. Additionally supported by HV: any sub-type of Number andCharSequence.

Verify that the annotated element value is less than or equal to the value specified by @DecimalMax

@DecimalMin(value=x)

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

java.util .Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.

Verify that the annotated element value (date type) is later than the current time

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 evaluated), any sub-type of Number.

Verify that the element value of the annotation is less than or equal to the value specified by @Max

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 evaluated), any sub-type of Number.

Verify that the element value of the annotation is greater than or equal to the value specified by @Min

@NotNull

##Any type

Verify that the annotated element value is not null

@Null

Any type

Validate the annotated element The value is null

##@Past

##java.util.Date, java.util .Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.

Verify that the annotated element value (date type) is earlier than the current time

##String. Additionally supported by HV: any sub-type of CharSequence.

Verify that the annotated element value matches the specified regular expression

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

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

Any non-primitive type (reference type)

Verify the associated object. For example, if there is an order object in the account object, specify Validate order object

CharSequence

,
,

Map and Arrays

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

@Range(min=minimum value, max=maximum value)

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

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

@NotBlank

##CharSequence

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

CharSequence

Verify that the element value of the annotation is Email, or you can specify a custom one through regular expressions and flags email format

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn