the Validator was originally designed for use with the Struts framework. However, because of its flexible design, there's no direct coupling to any Struts components, and you're free to use it in ordinary Java applications as well. There are, however, some steps that you'll have to take in order to make the Validator easier to digest.
You can utilize the same configuration files as in Web- based applications. This is another advantage of using the Validator framework. The Struts framework finds and loads these files based on the addition of the plug-in mentioned earlier. However, in non-Struts applications, the manner in which these configuration files are discovered and loaded must be done manually. This is typically done at application startup using the following method calls:
ValidatorResources resources = new ValidatorResources();This snippet of code creates a new instance of a
InputStream rules = ValidateExample.class.getResourceAsStream("validator-rules.xml");
ValidatorResourcesInitializer.initialize(resources, in);
InputStream forms = ValidateExample.class.getResourceAsStream("validation.xml");
ValidatorResourcesInitializer.initialize(resources, forms);ValidatorResources class and initializes it based on the two Validator configuration files. The ValidatorResources object can then be used throughout your application to validate the configured JavaBeans.
how to validate your beans using the Validator:// Suppose we already had a CheckoutForm object created and populated
CheckoutForm form = new CheckoutForm();
// Create a validator with the checkoutForm
Validator validator = new Validator(resources, "checkoutForm");
// Tell the validator which bean to validate against.
validator.addResource(Validator.BEAN_KEY, form);
// Validate the checkoutForm object and store the validation resultsValidatorResults results = validator.validate();
you can see that the name of the JavaBean checkoutForm is being passed to the constructor of the Validator class. This is necessary so that the Validator instance knows which set of validation rules to use against the bean.
As you can see, using the Validator with non-Struts applications is a little less automatic, but still provides a more flexible solution. The other benefit is that it keeps the validation rules out of the source code and in external configuration files. This can save time when customization of your application is a vital aspect of your business.
No comments:
Post a Comment