SpringMVC (6) data verification
In the SpringMVC series (4) Data Binding-1 and SpringMVC series (5) Data Binding-2, we show how to bind data and how to ensure the correctness of the data we get after the data is bound? This is what we will talk about in this article-> data verification.
Here we use Hibernate-validator for verification, Hibernate-validator achieves the JSR-303 verification framework to support annotation style verification. First, we need.
Configure the springservlet-config.xml files in the previous project as follows:
Where Classpath: validatemessages is the file where the annotation verification message is located. We need to add it in the resources folder.
Add ValidateController. java 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, 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 {// return to the form page if (result. hasErrors () return test (model); return validatesuccess ;}}
Here, @ Valid @ ModelAttribute (contentModel) ValidateModel validateModel @ Valid means to verify the data after it is bound to @ ModelAttribute (contentModel.
Add ValidateModel. java 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 content to the file validatemessages. properties where the annotation verification message is located:
Name. not. empty = name cannot be blank. Age. not. inrange = age out of range. Email. not. correct = the email address is incorrect. Email. not. empty = email is not for fear.
Name. not. empty corresponds to ValidateModel. the xxx name in the message = "xxx" in the java file. The following content is the ASCII code that is automatically converted when you enter Chinese characters. Of course, you can also directly write xxx as the prompt content, instead of creating another validatemessages. the properties file is added again, but this is not the correct method, because it is hard-coded and there is no way to internationalize it.
Add the validatetest. jsp and validatesuccess. jsp views in the views folder. The content is as follows:
<%@ page language=java contentType=text/html; charset=UTF-8 pageEncoding=UTF-8%><%@ taglib prefix=form uri=http://www.springframework.org/tags/form %>
Name:
Age:
Email:
<%@ page language=java contentType=text/html; charset=UTF-8 pageEncoding=UTF-8%>
Verification Successful!
In particular, it should be noted that in the validatetest. jsp View The name xxx after modelAttribute = xxx must be the same as the name xxx in @ Valid @ ModelAttribute (xxx); otherwise, the model data and error information cannot be bound.
The error message of the model attribute is displayed. When path = *, the error message of all model attributes is displayed.
Run the test:
Click Submit directly:
The error message is displayed correctly.
Enter the wrong data and submit it:
The error message is displayed correctly.
Enter the correct data and submit it:
The verification is successful.
The following are the main verification Notes and Instructions:
Annotation |
Applicable Data Types |
Description |
@ AssertFalse |
Boolean, boolean |
Verify that the annotation element value is false |
@ AssertTrue |
Boolean, boolean |
Verify that the annotation element value 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 annotation element value 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 types. Additionally supported by HV: any sub-type of Number andCharSequence. |
Verify that the annotation element value is less than or equal to the value specified by @ DecimalMin |
@ Digits (integer = integer Digits, fraction = decimal places) |
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 the integer digits of the element value of the annotation and the maximum number of decimal places |
@ Future |
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. |
The element value (date type) of the verification annotation 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 evaluated), any sub-type of Number. |
Verify that the annotation element value 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 evaluated), any sub-type of Number. |
Verify that the annotation element value is greater than or equal to the value specified by @ Min |
@ NotNull |
Any type |
Verify that the annotation element value is not null |
@ Null |
Any type |
Verify that the annotation element 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. |
The element value (date type) of the verification annotation is earlier than the current time |
@ Pattern (regex = regular expression, flag =) |
String. Additionally supported by HV: any sub-type of CharSequence. |
Verify that the element value of the annotation matches the specified regular expression. |
@ Size (min = minimum, max = maximum) |
String, Collection, Map and arrays. Additionally supported by HV: any sub-type of CharSequence. |
Verify that the annotation element values are within the min and max (inclusive) specified intervals, such as the character length and set size. |
@ Valid |
Any non-primitive type (reference type) |
Verifies the associated object. For example, if an order object exists in the account object, the Order object is verified. |
@ NotEmpty |
CharSequence ,Collection ,Map and Arrays
|
The element value of the verification annotation is not null and not empty (the string length is not 0, and the set size is not 0) |
@ Range (min = minimum, max = maximum) |
CharSequence, Collection, Map and Arrays,BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types
|
Verify that the annotation element values are between the minimum and maximum values. |
@ NotBlank |
CharSequence
|
The element value of the verification annotation is not empty (not null, the length is 0 after the first space is removed), different from @ NotEmpty, @ NotBlank: only applies to strings and removes spaces of strings during comparison. |
@ Length (min = lower limit, max = upper limit) |
CharSequence
|
Verify that the length of the element value of the annotation is within the min and max ranges. |
@ Email |
CharSequence
|
Verify that the annotation element value is Email. You can also use a regular expression and flag to specify a custom email format. |
For more information, see the official documentation: http://docs.jboss.org/hibernate/validator/4.3/reference/en-US/html/validator-usingvalidator.html