The principle and use of Java Validator

Source: Internet
Author: User
Tags ibm developerworks

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:

    1. @NotNull (message = "The ID of employee can is not NULL")
    2. 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:

  1. Target element type for @Target ({}) /constraint annotation app
  2. @Retention () //Constrain the timing of the annotation application
  3. @Constraint (Validatedby ={}) //validator associated with constraint annotations
  4. Public @interface constraintname{
  5. String message () default ""; //constraint annotation validation when output message
  6. Class[] Groups () default {}; //constraint annotations the group to which the validation occurred
  7. Classextends payload>[] Payload () default {}; //Constraint annotations payload
  8. }

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:

  1. @Target ({METHOD, FIELD, Annotation_type, CONSTRUCTOR, PARAMETER})
  2. @Retention (RUNTIME)
  3. @Documented
  4. @Constraint (Validatedby = {notemptyvalidator. Class})
  5. Public @interface Notempty {
  6. String message () The default "This string may be empty";
  7. Class[] Groups () default {};
  8. Classextends payload>[] Payload () default {};
  9. }

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:

    1. Public Interface Constraintvalidator<a < span= "" >extends Annotation, t> {
    2. void Initialize (A constraintannotation);
    3. Boolean IsValid (T value, Constraintvalidatorcontext context);
    4. }

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:

  1. Public class Notemptyvalidator implements Constraintvalidator<notempty, string>{
  2. Public Void Initialize (Notempty parameters) {
  3. }
  4. Public Boolean IsValid (String string,
  5. Constraintvalidatorcontext Constraintvalidatorcontext) {
  6. if (string = = null) return false;
  7. else if (String.Length () <1) return false;
  8. Else return true;
  9. }
  10. }

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:

    1. @NotEmpty
    2. Private String Company;

Then add the following code listing to the main function:

    1. String company = new String ();
    2. Employee.setcompany (company);

Run the program again and the output is:

    1. The ID of employee can is not null
    2. This string could be empty
    3. 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:

  1. Public @interface constraintname{
  2. String message () default "";
  3. Class[] Groups () default {};
  4. Classextends payload>[] Payload () default {};
  5. @Target ({METHOD, FIELD, Annotation_type, CONSTRUCTOR, PARAMETER})
  6. @Retention (RUNTIME)
  7. @Documented
  8. @interface List {
  9. Constraintname[] Value ();
  10. }
  11. }

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:

  1. @Target ({METHOD, FIELD, Annotation_type, CONSTRUCTOR, PARAMETER})
  2. @Retention (RUNTIME)
  3. @Documented
  4. @Constraint (Validatedby = patternofstringvalidator. Class)
  5. Public @interface patternofstring {
  6. String Mustcontainletter ();
  7. String message () of the default "this pattern is not is right ";
  8. Class[] Groups () default {};
  9. Classextends payload>[] Payload () default {};
  10. @Target ({METHOD, FIELD, Annotation_type})
  11. @Retention (RUNTIME)
  12. @interface List {
  13. Patternofstring[] Value ();
  14. }
  15. }

The validator for the constraint annotation corresponds to the verifier shown in Listing 10:

 Listing 10:

  1. Public class Patternofstringvalidator implements Constraintvalidator
  2. {
  3. Private String Letterin;
  4. Public Void Initialize (patternofstring parameters) {
  5. This.letterin=parameters.mustcontainletter ();
  6. }
  7. Public Boolean IsValid (String string,
  8. Constraintvalidatorcontext Constraintvalidatorcontext) {
  9. if (String.contains (Letterin))
  10. return true;
  11. return false;
  12. }
  13. }

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:

    1. @PatternOfString. List ({
    2. @PatternOfString (Mustcontainletter = "CH",
    3. Message = "It does not belong to China"),
    4. @PatternOfString (mustcontainletter="MainLand",
    5. Message="It does not belong to MainLand")})
    6. Private String Place;

Then add the following code listing to the main function:

    1. String place = "C";
    2. Employee.setplace (place);

Run the program again and the output is:

    1. It does not belong to MainLand
    2. It does not belong to China
    3. This string could be empty
    4. The ID of employee can is not null
    5. The size of employee ' s name must between 1 and ten

If place is assigned to a String, then the output is:

    1. This string could be empty
    2. The ID of employee can is not null
    3. It does not belong to MainLand
    4. 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:

  1. @NotNull
  2. @Size (min = 1)
  3. @Target ({METHOD, FIELD, Annotation_type, CONSTRUCTOR, PARAMETER})
  4. @Retention (RUNTIME)
  5. @Documented
  6. @Constraint (Validatedby = {NotEmptyValidator2. Class})
  7. Public @interface NotEmpty2 {
  8. String message () The default "This string may be empty";
  9. Class[] Groups () default {};
  10. Classextends payload>[] Payload () default {};
  11. @Target ({METHOD, FIELD, Annotation_type})
  12. @Retention (RUNTIME)
  13. @interface List {
  14. Notempty2[] Value ();
  15. }
  16. }

The principle and use of Java Validator

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.