September 1, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

JSF 2.0 Bean Validation and Dependency Injection

  • May 4, 2010
  • By Sangeetha S, Nitin KL, Ananya S
  • Send Email »
  • More Articles »

Data validation is such a common functionality in different tiers of Java applications that JSR 303 - bean validation, part of Java EE 6, provides a mechanism to define data validation constraints in a way that is independent of the application tier. This JSR allows you to specify data-validation constraints using annotations.

You can place these annotations on any field, method or class that follows the JavaBean naming convention. You can either use standard annotations (defined in the javax.validation.constraints package) or write your own custom annotations for specifying constraints.

The table below describes standard bean validation annotations:

Bean Validation Annotation Constraint Imposed on the Annotated Element
@NotNull Cannot be null
@Min Must be a number whose value must be higher or equal to the specified minimum
@Max Must be a number whose value must be lower or equal to the specified maximum
@Size Must be between specified minimum and maximum limits
@Pattern Must match the specified Java regular expression

The new release of JavaServer Faces, JSF 2.0, provides built-in support for bean validation if the server runtime (such as Java EE 6) requires it. You can also use it with Hibernate Validator (the reference implementation of JSR 303) in an environment where a Java EE 6 server may not be present.

Managed bean properties are mapped to UIInput components on the form; so you can place the standard validation constraints on them. The JSF implementation can apply the validation constraints on the component's values and capture any error message as FacesMessage, so that you can display them using h:messages or h:message.

As an example, suppose you used a JSF 2.0 custom component to create the registration view for a simple online quiz application. (Refer to JSF 2.0: Creating Composite Components for details on how you would do this.) To learn how to use bean validation, you will remodel the RegistrationBean from the online quiz application's registration view to include validation constraints on the property fields as shown below:

@ManagedBean
@RequestScoped
public class RegisterBean2 {
    @Size(min = 1, message = "Please enter the Email")
    @Pattern(regexp = "[a-zA-Z0-9]+@[a-zA-Z0-9]+\\.[a-zA-Z0-9]+", message = "Email format is invalid.")
    private String email;
   
    @Size(min = 1, message = "Please enter a Username")
    private String userName;

    @Size(min = 1, max = 10, message = "Password is mandatory and cannot contain more than 10 characters")
    private String password;

    @Size(min = 1, message = "Enter password in Confirm Password field")
private String confirmPassword;

    @NotNull(message = "Please enter Date of birth")
    private Date dob;

   //... no other change required
}


You can impose the mandatory constraint using the @NotNull annotation, as in the case of the dob field. For the email, username and password fields, you cannot use @NotNull as the default values for these would be an empty string and not null. Hence, no validation error will be generated if @NotNull is used. Instead, you can use @Size and specify the minimum boundary as 1. In addition, every constraint annotation has a message element that accepts a string. Its value will be used to build an error message that will be translated into FacesMessage and displayed in the response view using h:messages or h:message.

Now, you can modify the composite component register.xhtml. You can remove the mandatory field validation (done using required="true") because you have imposed this constraint on the managed bean properties. Similarly, you can also remove the <f:validateRegex> tag as shown below:

<h:outputText value="#{cc.attrs.emailPrompt}"/>
<h:inputText id="email"  value="#{cc.attrs.managedBean.email}" >
<!--  
<f:validateRegex pattern="[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+"/> 
-->
</h:inputText>


You can now test the bean validation support. Figure 1 shows a sample output from submitting the form without entering any values.


Figure 1. Testing Bean Validation Support in Online Quiz App:
Here is a sample output from submitting the registration form without entering any values.

JSF 2 also provides a <f:validateBean> tag that allows you to use validation groups. A validation group defines a subset of constraints; every constraint belongs to one or more groups. You can specify the validation group(s) to be considered during the validation of a component by using the validationGroups attribute as shown below:

<h:inputText value="#{bean.prop1}"> 

<f:validateBean validationGroups="com.demo.validation.groups.Group1"/> 
</h:inputText>



Tags: annotations, JavaServer Faces, JSF 2.0, Dependency injection, Bean validation



Page 1 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel