Spring MVC parameter Check

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/eson_15/article/details/51725470

This blog post mainly summarizes the validation of data in Springmvc. In practice, often use more is the front-end of the check, such as the page JS check, for high security requirements of the recommendations on the service side also to be verified. The service-side check can be in the control layer Conroller, can also be in the business layer Service,controller Verify the validity of the parameters of the page request, in the service-side control layer Conroller check, do not distinguish between the client type (browser, mobile client, remote Call) The service layer primarily verifies key business parameters and is limited to the parameters used in the service interface. Here is the main summary of how to use the controller in the Springmvc check.

1. Environmental Preparedness

  In SPRINGMVC we use Hibernate's check frame validation (note: There is nothing to do with Hibernate), and with this check frame, you need to import the jar package (), as follows:

2. Configuring the Validator

  Configure the validator in the Springmvc.xml configuration file as follows:

<!--Configuring the Validator -<BeanID= "Validator"class= "Org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">    <!--validator, using Hibernate validator -    < Propertyname= "Providerclass"value= "Org.hibernate.validator.HibernateValidator"/>    <!--Specify the resource file used by the checksum, configure the checksum error message in the file, and use the classpath validationmessages.properties file if not specified by default -    < Propertyname= "Validationmessagesource"ref= "Messagesource"/></Bean><!--Verifying the error message configuration file -<BeanID= "Messagesource"class= "Org.springframework.context.support.ReloadableResourceBundleMessageSource">    <!--Resource File name -    < Propertyname= "Basenames">        <List>            <value>Classpath:customvalidationmessage</value>        </List>    </ Property>    <!--resource file Encoding format -    < Propertyname= "Fileencodings"value= "Utf-8"/>    <!--cache time for resource file content, in seconds -    < Propertyname= "Cacheseconds"value= "+"/></Bean>

  The configuration rule is the bean and property properties, do not write the class and file name is wrong, there is a configuration is a resource file name, this file we will configure some error message. After you have configured the validator, you need to inject the officer into the processor adapter, or in the Springmvc.xml file, inject our well-equipped validator into it as follows:

  This verifies that the checker is configured.

3. Add a check in the Pojo

  The Hibernate validation Framework provides a lot of annotation validation, and I'll start by simply listing:

Annotations Run-time check
@AssertFalse The annotated element must be false
@AssertTrue The annotated element must be true
@DecimalMax (value) The annotated element must be a number whose value must be less than or equal to the specified minimum value
@DecimalMin (Value) The annotated element must be a number whose value must be greater than or equal to the specified minimum value
@Digits (integer=, fraction=) The annotated element must be a number whose value must be within an acceptable range
@Future The annotated element must be a date and check whether the given date is later than the present
@Max (value) The annotated element must be a number whose value must be less than or equal to the specified minimum value
@Min (value) The annotated element must be a number whose value must be greater than or equal to the specified minimum value
@NotNull The annotated element must not be null
@Null The annotated element must be null
@Past (Java.util.date/calendar) The annotated element must be past the date, and the value in the dimension object is checked to indicate that the date is earlier than the current
@Pattern (regex=, flag=) The annotated element must conform to a regular expression to check whether the string matches the regex-defined regular expression in the match-specified case
@Size (min=, max=) The annotated element must be in the scope of the formulation (data type: String, Collection, Map and arrays)
@Valid Recursive validation of the associated object, if the associated object is a collection or an array, then the elements in the recursive check, if it is a map, the value of the part of the validation
@CreditCardNumber Make a rough verification of the credit card number
@Email The annotated element must be an e-mail address
@Length (min=, max=) The annotated object must be the size of the string must be within the scope of the formulation
@NotBlank The annotated object must be a string, cannot be empty, and a space is ignored when checking
@NotEmpty The annotated object must be empty (data: string,collection,map,arrays)
@Range (min=, max=) The annotated element must be within the appropriate range (data: BigDecimal, BigInteger, String, Byte, short, int, long and the wrapper class of the original type)
@URL (protocol=, host=, port=, regexp=, flags=) The annotated object must be a string, check if it is a valid URL, and if Protocol,host is provided, the URL should also meet the conditions provided

  The above I briefly listed some of the verification of the annotations, the specific use of different annotations can refer to official documents or online information, here I choose two annotations to illustrate how to use this Hibernate authentication framework. First, add the corresponding validation annotations on the attributes that you want to verify in your Pojo:

  We see the note can specify the message, then the content in this message is the error message configuration file corresponding to the key, the corresponding error message is taken out, so for these two error messages, we write a configuration file:

4. Capturing the checksum error message

  The above has been officer the relevant configuration is well-equipped, the next step in the controller's method to capture the error message in the validation results, and then send these error messages to the foreground to display. So how do you capture the controller's approach? As follows:

  As you can see, add @validated to the front of the pojo that needs verification, add Bindingresult Bindingresult behind the Pojo that needs verification to receive the checksum error message. It is noteworthy that the @Validated and Bindingresult Bindingresult are paired and the formal parameter order is fixed (one after the other). This will allow you to receive the error message successfully. I won't write anything about the front desk.

5. Group Check

  The above has been able to complete the SPRINGMVC calibration function, but there is a problem: just in the Pojo defined the validation rules, but Pojo is used by multiple controllers, now if two different controllers use the same calibration rules, simply speaking, A controller does not need to verify the production date, just check the name of the product, the other controller two to be verified, so that can not be done, because two controllers are using the same pojo.
  To solve this problem, we can define multiple check groupings (actually a Java interface), which rules are defined in the grouping, and each controller method uses a different checksum grouping. Take a look at the following example to understand:
  First define a check group:

 Public Interface ValidGroup1 {    /// interfaces do not need to define any method, just    group different check rules // This group only check the length of the product name }

 

  Then we add this grouping in just Pojo, as follows:

  And look at how the controller that wants to verify the Name field is configured:

  In this way, the controller will not be able to verify the field of the production date, which can be resolved by different controllers to check the different fields of the problem.
  

Spring MVC parameter Check

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.