Using the Validator class

Before the create method of a facade class is used to add the license to the database, we need to validate the values for the fields. The Validator class provides this capability. It allows an object to be checked to see if any of the fields have failed to meet its validation criteria.

Getting ready

We will use the LicenseBean and LicenseBeanFacade classes from the ValidationApplication as discussed in the Validating persistent fields and properties recipe.

How to do it...

In order to demonstrate this approach we need to modify both the LicenseBean and the LicenseServlet. First, modify the field declarations of the LicenseBean as shown here:

public class LicenseBean implements Serializable {
@Size(min=12)
@NotNull
private String name;
@Future
@Temporal(javax.persistence.TemporalType.DATE)
private Date dateOfBirth;
@Pattern(regexp="C??A??6??N??")
private String restrictions;
@AssertFalse
private boolean resident;
@Min(12)
@Max(48)
private int monthsToExpire;
...
}

Next, replace the try block in the LicenseServlet with the following code:

try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet LicenseServlet</title>");
out.println("</head>");
out.println("<body>");
license = new LicenseBean();
license.setName("Pax Maxwell");
Calendar calendar = Calendar.getInstance();
calendar.set(1981, 4, 18);
license.setDateOfBirth(calendar.getTime());
license.setMonthsToExpire(50);
license.setResident(true);
license.setRestrictions("CT6");
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set constraintViolations = validator.validate(license);
Iterator iter = constraintViolations.iterator();
if (iter.hasNext()) {
while (iter.hasNext()) {
ConstraintViolation constraintViolation = (ConstraintViolation) iter.next();
out.println("<h3>Message: " + constraintViolation.getMessage());
out.println(" however value given was: " + constraintViolation.getInvalidValue() + "</h3>");
}
} else {
licenseBeanFacade.create(license);
out.println("<h1>Name: " + license.getName() + " - License ID: " + license.getId() + "</h1>");
}
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}

Execute the application using the URL found in the following screenshot:

How to do it...

How it works...

The LicenseBean class's declarations have been annotated to use various validators illustrated in the previous set of validation recipes. For example, the minimum of the name field is 12. The reader is encouraged to experiment with other settings.

In the LicenseServlet, a Validator instance was obtained using the static buildDefaultValidatorFactory method to return an instance of a ValidatorFactory interface. In this example, the object returned was not explicitly saved, but was chained with its getValidator method to return a Validator object.

The Validator uses a validate method which is passed the object to be validated and returns a Set of ConstraintViolations. Using the ConstraintViolation object, an Iterator object was returned from the set. If it was not empty, then the constraint violations were displayed. Otherwise, the servlet continued normally.

There were two ConstraintViolation methods used to display the violations:

  • getMessage This returned a message describing the violation
  • getInvalidValue Returned the value which caused the violation

They can be used to display information about the violations or used to isolate and deal with violations.

In this simple application, we dealt with the violations by displaying them. In a more robust application we would need to determine and act upon each violation in a

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.78.102