Http://developer.51cto.com/art/201104/253257_1.htm
Ava EE 6 Core features: Bean validation features Overview (2) 2011-04-02 14:33 Zhang Guanan Chen Zhijian IBM developerWorksfont Size:T | T
Data validation occupies an important place in the application development of Java hierarchy. Java EE 6 proposes a bean Validation specification that uses annotations to validate Java beans in a way that is not limited to a certain level or a programming model, and is flexible to use. This article will introduce you to the various features of the specification for your system.
AD:WOT2015 Internet operations and developers Conference selling tickets
Definition of Constraints
Constraint annotations
The Bean Validation specification includes two parts, one is constraint annotation, the @NotNull in Listing 1 is constraint annotation, the other is constraint validator, each constraint annotation has a corresponding constraint validator, and the constraint validator is used to verify the specific Java Bean Whether the condition of the constraint annotation declaration is satisfied.
In Java beans, annotations that constrain a method, field, property, or its combination form, are constraint annotations, as shown in Listing 2:
Listing 2:
- @NotNull (message = "The ID of employee can is not NULL")
- Private Integer ID;
The meaning of Listing 2 is: For the field ID, the value in the instance of the Java Bean cannot be empty. For each constraint annotation, it must be defined before it is actually used. The JSR303 specification provides several definitions of constraint annotations by default (see table 1), and we can extend the API provided by the specification to implement constraint annotations that meet our business needs.
Table 1. Definition of constraint annotations embedded in the Bean Validation specification
Constraint Note name |
Constraint annotation Description |
@Null |
Verifies whether the object is empty |
@NotNull |
Verifies whether the object is non-empty |
@AssertTrue |
Verify that the Boolean object is True |
@AssertFalse |
Verify that the Boolean object is False |
@Min |
Verifies that number and String objects are large equal to the specified value |
@Max |
Verifies that number and String objects are small equal to the specified value |
@DecimalMin |
Verifies that number and String objects are large equal to the specified value, with decimals having precision |
@DecimalMax |
Verifies that number and String objects are small equal to the specified value, with decimals having precision |
@Size |
Verifies whether the length of the object (array,collection,map,string) is within a given range |
@Digits |
Verify that the composition of number and String is legal |
@Past |
Verify that date and Calendar objects are before the current time |
@Future |
Verify that date and Calendar objects are after the current time |
@Pattern |
Rules that verify whether a String object conforms to a regular expression |
Constraint annotations like ordinary annotations, a typical definition of constraint annotations should include at least the following (Listing 3):
Listing 3:
- Target element type for @Target ({}) /constraint annotation app
- @Retention () //Constrain the timing of the annotation application
- @Constraint (Validatedby ={}) //validator associated with constraint annotations
- Public @interface constraintname{
- String message () default ""; //constraint annotation validation when output message
- Class[] Groups () default {}; //constraint annotations the group to which the validation occurred
- Classextends payload>[] Payload () default {}; //Constraint annotations payload
- }
The target element types for constraint annotation applications include METHOD, FIELD, type, Annotation_type, CONSTRUCTOR, PARAMETER. Method constraints related getter methods; FIELD constraint-related attributes; TYPE constrains the specific Java Bean; Annotation_type is used in composite constraints, and the specification also supports constraints on parameters (PARAMETER) and Constructors (CONSTRUCTOR).
The group attributes for validation are described in detail in groups and group sequences in the third most part of this article.
The payload is typically used to correlate some metadata information with the constraint annotations, and one common scenario is to use the payload to indicate the severity of the validation results.
Listing 4 shows the definition of a constraint annotation with a validation string that is not NULL:
Listing 4:
- @Target ({METHOD, FIELD, Annotation_type, CONSTRUCTOR, PARAMETER})
- @Retention (RUNTIME)
- @Documented
- @Constraint (Validatedby = {notemptyvalidator. Class})
- Public @interface Notempty {
- String message () The default "This string may be empty";
- Class[] Groups () default {};
- Classextends payload>[] Payload () default {};
- }
Once the constraint annotation definition is complete, you need to implement the validator associated with the constraint annotation at the same time. The implementation of the constraint verifier needs to extend the interface Javax.validation.ConstraintValidator provided by the JSR303 specification. Listing 5 shows the interface.
Listing 5:
- Public Interface Constraintvalidator<a < span= "" >extends Annotation, t> {
- void Initialize (A constraintannotation);
- Boolean IsValid (T value, Constraintvalidatorcontext context);
- }
The interface has two methods, the method initialize to instantiate the validator, it must be invoked before the instance of the validator is used, and ensure the correct initialization of the validator, its parameters are constraint annotations; method IsValid is the principal method for constraint validation, where value The parameter represents the instance that needs to be validated, and the context parameter represents the contextual environment in which the constraint executes.
For the constraint annotations defined in Listing 4, listing 6 shows the implementation of the validator corresponding to the annotation.
Listing 6:
- Public class Notemptyvalidator implements Constraintvalidator<notempty, string>{
- Public Void Initialize (Notempty parameters) {
- }
- Public Boolean IsValid (String string,
- Constraintvalidatorcontext Constraintvalidatorcontext) {
- if (string = = null) return false;
- else if (String.Length () <1) return false;
- Else return true;
- }
- }
At this point, a constraint annotation that can be declared and used has been defined, and listing 7 shows the use of the constraint annotation in the actual program. To save space, here are only additions and modifications to Listing 1, not all of the sample code, you can get all the code in the appendix to this article.
Listing 7:
First, add the field Company and the corresponding getter and setter methods to the class Employee in Listing 1:
- @NotEmpty
- Private String Company;
Then add the following code listing to the main function:
- String company = new String ();
- Employee.setcompany (company);
Run the program again and the output is:
- The ID of employee can is not null
- This string could be empty
- The size of employee ' s name must between 1 and ten
Multi-value constraints
The following describes a feature of the Bean Validation specification, a multivalued constraint (multiple Constraints): For the same target element, you can use different attributes at the same time to achieve the purpose of multi-value verification of the target element when making a constraint annotation declaration. As shown in Listing 8:
Listing 8:
- Public @interface constraintname{
- String message () default "";
- Class[] Groups () default {};
- Classextends payload>[] Payload () default {};
- @Target ({METHOD, FIELD, Annotation_type, CONSTRUCTOR, PARAMETER})
- @Retention (RUNTIME)
- @Documented
- @interface List {
- Constraintname[] Value ();
- }
- }
Implementing a multivalued constraint only requires defining a List (@interface list{}) while defining the constraint annotations. When using this constraint annotation, the Bean Validation each element inside the value array as a common constraint annotation and validates it, and all constraints are met before validation passes.
Listing 9 defines a constraint annotation, which is used to verify that a string contains the specified content.
Listing 9:
- @Target ({METHOD, FIELD, Annotation_type, CONSTRUCTOR, PARAMETER})
- @Retention (RUNTIME)
- @Documented
- @Constraint (Validatedby = patternofstringvalidator. Class)
- Public @interface patternofstring {
- String Mustcontainletter ();
- String message () of the default "this pattern is not is right ";
- Class[] Groups () default {};
- Classextends payload>[] Payload () default {};
- @Target ({METHOD, FIELD, Annotation_type})
- @Retention (RUNTIME)
- @interface List {
- Patternofstring[] Value ();
- }
- }
The validator for the constraint annotation corresponds to the verifier shown in Listing 10:
Listing 10:
- Public class Patternofstringvalidator implements Constraintvalidator
- {
- Private String Letterin;
- Public Void Initialize (patternofstring parameters) {
- This.letterin=parameters.mustcontainletter ();
- }
- Public Boolean IsValid (String string,
- Constraintvalidatorcontext Constraintvalidatorcontext) {
- if (String.contains (Letterin))
- return true;
- return false;
- }
- }
If you want to verify that a string contains two substrings at the same time, the multivalued constraint becomes more important, and listing 11 details the use of the multivalued constraint.
Listing 11:
Add the following fields to the class Employee in Listing 1, and the corresponding getter and setter methods:
- @PatternOfString. List ({
- @PatternOfString (Mustcontainletter = "CH",
- Message = "It does not belong to China"),
- @PatternOfString (mustcontainletter="MainLand",
- Message="It does not belong to MainLand")})
- Private String Place;
Then add the following code listing to the main function:
- String place = "C";
- Employee.setplace (place);
Run the program again and the output is:
- It does not belong to MainLand
- It does not belong to China
- This string could be empty
- The ID of employee can is not null
- The size of employee ' s name must between 1 and ten
If place is assigned to a String, then the output is:
- This string could be empty
- The ID of employee can is not null
- It does not belong to MainLand
- The size of employee ' s name must between 1 and ten
It can be seen that the constraint verifies the two constraint annotations that are declared separately, as long as there is a Java Bean instance that does not conform to the constraint validation rule, and the corresponding validation failure information is generated. When constraining annotation declarations, different output information can be given using the message parameter according to different constraint values.
Combining constraints
The following is another important feature in the Bean Validation specification: Composite constraints. The Bean Validation specification allows the combination of different constraints to create higher-level and more functional constraints, thus avoiding the reuse of atomic-level constraints. The constraint annotations @NotEmpty defined in Listing 4 are used to determine that a string is at least 1 in length on a non-empty basis, and its actual meaning is equivalent to the combination of @NotNull and @Size (min=1), so @NotEmpty constraints can be defined as composite constraints NotEmpty2, as shown in Listing 12:
Listing 12:
- @NotNull
- @Size (min = 1)
- @Target ({METHOD, FIELD, Annotation_type, CONSTRUCTOR, PARAMETER})
- @Retention (RUNTIME)
- @Documented
- @Constraint (Validatedby = {NotEmptyValidator2. Class})
- Public @interface NotEmpty2 {
- String message () The default "This string may be empty";
- Class[] Groups () default {};
- Classextends payload>[] Payload () default {};
- @Target ({METHOD, FIELD, Annotation_type})
- @Retention (RUNTIME)
- @interface List {
- Notempty2[] Value ();
- }
- }
The principle and use of Java Validator