SPRINGMVC configuration Data Validation ()

Source: Internet
Author: User

1. Additional Hibernate-validator in Pom.xml

2. Append JSR-303 annotations to the domain of the DTO class

 Public class DataS {    = "1993*", message = "Birthday Must start with 1993")    private  String dt;     /** */}

3. Append @valid to the DTO parameter of the incoming controller and append the Bindingresult object

@RequestMapping (value = "Json_str") @ResponseBody PublicString jsonstr (@Valid @RequestBody DataS DataS, Bindingresult checker) {Log.info ("Request Start"); if(Checker.haserrors ()) {List<ObjectError> errors =checker.getallerrors (); StringBuilder Messages=NewStringBuilder (400);  for(Objecterror error:errors) {messages.append (Error.getdefaultmessage ()); } log.error ("Request failed:" +messages.tostring ()); return"Failue"; } log.info ("Request Succeeded"); return"Sucess";} 

There is a special case,

Like a dto with an integer No field,

The front end illegally sends the data: {' No ': ' ABC '} of Ajax,

Then two no cannot bind to each other, and the value of Dto.getno () will be null,

So if you take Error.getdefaultmessage () as the request method Jsonstr, you will get the exception information like the following

Failed to convert property value of type ' java.lang.String ' to required type ' Java.lang.Integer ' for property ' no '; Nested exception is Java.lang.NumberFormatException:For input string: "ABC"

In this case, there is no doubt that the user has made an illegal request,

It is generally necessary to return the field name so that the front end tells the user "Please enter the correct format age",

Or return a more detailed error message.

The workaround is to add one-step judgment before taking Error.getdefaultmessage ().

@RequestMapping (value = "Json_str") @ResponseBody PublicString jsonstr (@Valid @RequestBody DataS DataS, Bindingresult checker) {Log.info ("Request Start"); if(Checker.haserrors ()) {List<ObjectError> errors =checker.getallerrors (); StringBuilder Messages=NewStringBuilder (400);  for(Objecterror error:errors) {if (stringutils.equals ("Typemismatch", Error.getcode ())) {Log.error ("Request failed: Parameter" + Error.getobjectnam E () + "field type mismatch:" + error.getdefaultmessage ()); Return "Failue";            } Messages.append (Error.getdefaultmessage ()); } log.error ("Request failed:" +messages.tostring ()); return"Failue"; } log.info ("Request Succeeded"); return"Sucess";} 

where Error.getcode () returns the contents of the annotations in the first column of the following table (e.g. "Notblank")

If data binding is unsuccessful because of a type conversion problem before the data is validated,

Returns a value of "Typemismatch", a special case that can be captured with an if statement block.

is equivalent to writing the message value in the note into the IF statement block. Instead of printing the exception information for the frame

4, quote the information on the Internet

validation Annotations Validating the data type 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
@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
@Min (value= value) Bigdecimal,biginteger, Byte, short, int, long, and so on any number or charsequence (stored as a numeric) subtype Verifies that the element value of the annotation is greater than or equal to the value specified by @min
@Max (value= value) Same as the @min requirements. Verifies that the element value of the annotation is less than or equal to the value specified by @max
@DecimalMin (value= value) Same as the @min requirements. Verifies that the element value of the annotation is greater than or equal to the value specified by @ decimalmin
@DecimalMax (value= value) Same as the @min requirements. Verifies that the element value of the annotation is less than or equal to the value specified by @ Decimalmax
@Digits (integer= integer digits, fraction= decimal place) Same as the @min requirements. To verify the integer and maximum number of decimal digits for the element value of the annotation
@Size (min= lower limit, max= upper limit) String, Collection, Map, array, etc. Verifies that the element value of the annotation is within a specified interval of min and max (inclusive), such as character length, collection size
@Past Java.util.Date, Java.util.Calendar; Joda date type of the time class library Verify that the annotation's element value (date type) is earlier than the current time
@Future Same as the @past requirements Verify that the annotation's element value (date type) is later than the current time
@NotBlank Charsequence Sub-type 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, that the @NotBlank is applied only to strings and that the first space of the string is stripped when compared
@Length (min= lower limit, max= upper limit) Charsequence Sub-type Validates the element value length of annotations within min and Max intervals
@NotEmpty Charsequence subtype, Collection, Map, array 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) Bigdecimal,biginteger,charsequence, Byte, short, int, long, etc. atomic type and packing type Verifies that the element value of the annotation is between the minimum and maximum values
@Email (regexp= Regular expression, flag= flag pattern) Charsequence subtype (such as String) Verify that the element value of the annotation is email, or you can specify a custom email format via REGEXP and flag
@Pattern (regexp= Regular expression, flag= flag pattern) String, the subtype of any charsequence Validates that the element value of the annotation matches the specified regular expression
@Valid Any non-atomic type Specifies the object that the recursive validation is associated with, such as having an Address object property in the user object, if you want to validate the address object together when validating the user object, then add @valid annotations on the Address object to cascade validation

SPRINGMVC configuration 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.