Server-Side Java Server Faces Validators: Design Details

This solution is illustrated by the validators application available under the bpcatalog project hosted at java.net.

This is an application using JavaServer[TM] Faces technologies to show multiple solutions for validations, both client-side JavaScript[TM] validation and server-side JavaServer Faces  validation.

Client Side Validation

The index.jsp file also contains JavaScript which validates the color field's content. Client-side validation does not work if the client browser does not support JavaScript or has JavaScript turned off. If validation fails, the browser does not post the form to the web application, reducing round trips which might be time and resource consuming. Applications should always be designed to do server-side validation, regardless of whether or not client side validation has been performed.

Server Side Validation

The application consists of two JavaServer pages: an index.jsp file and a response.jsp file. The index.jsp page contains all of the JavaServer Faces code examples all in a single page. The requests are forwarded to the response.jsp page if the data in the page is valid, or back to index.jsp where an error message is displayed in when validation fails.

There is a managed bean called ValidatorBean that contains the validation code used in the page. The following JavaServer Faces code in the index.jsp page uses a method binding expression to call the validate method on the ValidatorBean:
    <h:inputText id="smallNumber" value="#{ValidatorBean.smallNumber}"
validator="{JSFValidator.validate}"/>

The following code from the ValidatorBean is called when the JavaServer Faces page is processed.

 public void validate(FacesContext context,
UIComponent component,
Object value) throws ValidatorException {

if ((context == null) || (component == null)) {
throw new NullPointerException();
}
if (value != null) {
if (((String)value).equals("blueprints")) {
throw new ValidatorException(new FacesMessage("blueprints is invalid"));
}
}
}

© Sun Microsystems 2005. All of the material in The Java BluePrints Solutions Catalog is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.