JavaBeans Validation is a new validation model available as part of Java EE 6 platform. The Bean Validation model is supported by constraints in the form of annotations placed on a field, method, or class of a JavaBeans component, such as a managed bean.

JSR-303 Bean Validation specification allows us to generate the Java Bean validation. Bean Validation aims at standardizing constraint validation for the the Java platform. Validating data that eventually feeds into the domain model is a common task that is copied in many different layers of an application, from the presentation tier to the persistentce layer. Many times the exact same constraints and validation logic has to be duplicated in each separate validation framework, which is time-consuming and error-prone. More information about this specification can be found in the following link: http://jcp.org/en/jsr/detail?id=303

Red Hat has been heavily involved in the making of Java EE 6. Here are some of the specs RedHat has put a lot of effort into either by contributing heavily or by leading the standardization effort: Java Persistence 2, Java Server Faces 2, JSR-299 formely known as Web Beans, JSR-303 Bean Validation. More information about this can be found in the following interesting FAQ section: http://www.jboss.com/about/leadership/jsr/bernard.html

Features To Discuss.

In this example we will mainly focus on following points

Point-1). Here we are using JBoss AS7 latest build “jboss-as-7.1.0.CR1b” which can be downloaded from the following link: http://www.jboss.org/jbossas/downloads

Point-2). How to utilize Existing JSR-303 annotations “javax.validation.constraints.*” inside our application.

Point-3). How to create our own Custom Validation Rules (Annotations), Example E-Mail Address Validation @ValidateEMail(domain=”middlewaremagic.com”)

Point-4). Also we will see how to implement Bean Validation inside JSF2.0 @ManagedBean’s

Developing Web Application using JSR-303

Step1). Create a directory somewhere in your file system like “/home/userone/JSF2_BeanValidation_Demo” where we will place our application build related stuff. Then create another directory “src” inside “/home/userone/JSF2_BeanValidation_Demo” where we will be placing our source codes and JSPs.

Step2). Create Bean class “HelloBean.java” as following inside the “/home/userone/JSF2_BeanValidation_Demo/src” directory.

package org;
import java.io.Serializable;

// faces APIs
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

//Validation APIs
import javax.validation.constraints.Size;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import custom.validators.ValidateEMail;

public class HelloBean implements Serializable {
        @Size(min=4, max=240, message="The Name {javax.validation.constraints.Size.message}")
	private String name;
 	public String getName() {
		return name;
	public void setName(String name) {
		this.name = name;

        @NotNull (message="The Salary {javax.validation.constraints.NotNull.message}")
        @Max(value=50000, message="The Salary {javax.validation.constraints.Max.message}")
        @Min(value=25000, message="The Salary {javax.validation.constraints.Min.message}")
	private Integer salary;
 	public Integer getSalary() {
		return salary;
	public void setSalary(Integer salary) {
		this.salary = salary;

        // NOTE: - "custom.validators.ValidateEMail" is our Custom Validator Annotation.
        private String emailAddress;
        public String getEmailAddress() {
                return emailAddress;
        public void setEmailAddress(String emailAddress) {
                this.emailAddress = emailAddress;


Step3). Now we will create a Validator wich will validate whether an E-Mail address entered by the user has domain “middlewaremagic.com” or not? So we will create an Interface first with some name like “ValidateEMail.java” inside “/home/userone/JSF2_BeanValidation_Demo/src” directory as following:

package custom.validators;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;

@Constraint(validatedBy = ValidateEMail_Impl.class)
public @interface ValidateEMail {

    String message() default "E-Mail Address must belong to mail domain as {domain}";
    Class<?>[] groups() default {};
    String domain();
    Class<? extends Payload>[] payload() default {};

Step4). Now provide the implementation of the above interface “ValidateEMail_Impl.java” to provide the actual logic of the validation whether the E-Mail entered by user is containing “middlewaremagic.com” or not? So Place this file as well inside the “/home/userone/JSF2_BeanValidation_Demo/src” directory as following:

package custom.validators;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.StringTokenizer;

public class ValidateEMail_Impl implements ConstraintValidator<ValidateEMail, String> {

    private String domain;
    public void initialize(ValidateEMail constraintAnnotation) {
        System.out.println("nt initialize() called");
        String emailDomain = constraintAnnotation.domain();
        String msg = constraintAnnotation.message();

        if (emailDomain == null || emailDomain.equals("")) {
            throw new IllegalArgumentException("The email address specified in @"+ ValidateEMail.class.getSimpleName() + " must not be null.");

    public boolean isValid(String email,ConstraintValidatorContext constraintValidatorContext) {
        boolean valid=false;
        System.out.println("nt isValid() called");
        if (email == null)
               return false;
              StringTokenizer st=new StringTokenizer(email,"@");
              if(st.countTokens() == 2  )
                   st.nextToken();  // Ignoring first tooken
                   String emailDomain=getDomain();   // like   middlewaremagic.com
                       return valid;
                   return valid;
        return valid;

    public void setDomain(String domain)
      System.out.println("nt setDomain  called domain= "+domain);
    public String getDomain()
      System.out.println("nt getDomain  called ");
      return domain;

Step5). Now as we are going to use the Bean Validation inside JSF2.0 application so we will a simple “faces-config.xml”, Place this file as well inside the “/home/userone/JSF2_BeanValidation_Demo/src” directory as following:

<?xml version="1.0" encoding="UTF-8"?>
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"

    <!-- After adding the message-bundle make sure that we place "ApplicationMessages.properties" file inside "WEB-INF/classes" directory. -->


Step6). Now we will create “ApplicationMessages.properties” file, Place this file as well inside the “/home/userone/JSF2_BeanValidation_Demo/src” directory as following (We need to make sure that this file goes inside the “WEB-INF/classes” directory once the application is built.):

javax.validation.constraints.Min.message=must be greater than or equal to {value}
javax.validation.constraints.Max.message=must be less than or equal to {value}

javax.validation.constraints.Null.message=must be null
javax.validation.constraints.NotNull.message=must not be null

javax.validation.constraints.Past.message=must be a past date
javax.validation.constraints.Future.message=must be a future date

javax.validation.constraints.Size.message=size must be between {min} and {max}
javax.validation.constraints.Digits.message=numeric value out of bounds (<{integer} digits>.<{fraction} digits> expected)

javax.validation.constraints.AssertTrue.message=must be true
javax.validation.constraints.AssertFalse.message=must be false

javax.validation.constraints.Pattern.message=must match the following regular expression: {regexp}

custom.validators.ValidateEMail.message= E-Mail Address must belong to mail domain as {domain}

Step7). Now we will write simple “hello.xhtml” file inside “/home/userone/JSF2_BeanValidation_Demo/src” directory as following to provide a form to the user to enter some inputs:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns="http://www.w3.org/1999/xhtml"
        <title>JSF 2.0 Hello World</title>
    	<h3>JSF 2.0 Hello World Example - hello.xhtml</h3>
    	   <h:outputLabel id="usernameLabel" value="Enter UserName: "/> 
           <h:inputText id="usernameText" value="#{helloBean.name}">  </h:inputText>
           <h:message for="usernameText" errorStyle="color:red"/>


    	   <h:outputLabel id="salaryLabel" value="Enter Salary: "/> 
           <h:inputText id="salaryText" value="#{helloBean.salary}">  </h:inputText>
           <h:message for="salaryText" errorStyle="color:red"/>


    	   <h:outputLabel id="emailLabel" value="Enter emailAddress: "/> 
           <h:inputText id="emailText" value="#{helloBean.emailAddress}">  </h:inputText>
           <h:message for="emailText" errorStyle="color:red"/>


    	   <h:commandButton value="Welcome Me" action="welcome"></h:commandButton>

Step8). Now we will write simple “welcome.xhtml” file inside “/home/userone/JSF2_BeanValidation_Demo/src” directory as following to get the details entered by the user in previous xhtml form:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns="http://www.w3.org/1999/xhtml"    
    	<title>JSF 2.0 Hello World</title>
    <h:body bgcolor="white">
    	<h3>JSF 2.0 Hello World Example - welcome.xhtml</h3>
    	<h4>Welcome Mr.     <font color="green">#{helloBean.name}</font></h4>
    	<h4>Your Salary is  <font color="green">#{helloBean.salary} Rs/-</font></h4>
    	<h4>Your E-Mail is  <font color="green">#{helloBean.emailAddress}</font></h4>

Step9). Now we will write the “web.xml” file inside “/home/userone/JSF2_BeanValidation_Demo/src” directory as following:

<?xml version="1.0"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

 <display-name>TestJSF Bean Validation EE6</display-name>
  <servlet-name>Faces Servlet</servlet-name>

  <!-- Welcome page -->

  <!-- Map these files with JSF -->
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-name>Faces Servlet</servlet-name>

Building and Deploying Application

Step10). Now the most important part, here we are going to develop “build.xml” ANT file, which will build, deployour webapplication on the JBoss jboss-as-7.1.0.CR1b Server, so write the following “build.xml” file inside “/home/userone/JSF2_BeanValidation_Demo” directory.

<project name="JSR-303_Demo" default="deploy">
<property name="jboss.home" value="/home/userone/jboss-as-7.1.0.CR1b" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="basedir" value="." />
<property name="tmp.dir" value="tmp" />
<property name="output.dir" value="build" />
<property name="src.dir" value="src" />
<property name="war.context" value="EE6_BeanValidationDemo" />
<property name="war.name" value="${war.context}.war" />

        <path id="jboss.classpath">
           <fileset dir="${jboss.module.dir}">
              <include name="**/*.jar"/>

        <target name="init">
           <delete dir="${output.dir}" />
           <mkdir dir="${output.dir}" />
           <delete dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}" />
        <target name="build" depends="init">
           <mkdir dir="${tmp.dir}/WEB-INF/classes"/>
           <javac srcdir="${src.dir}" destdir="${tmp.dir}/WEB-INF/classes"  includes="*.java" classpathref="jboss.classpath" />
           <copy file="${src.dir}/hello.xhtml" todir="${tmp.dir}"/>
           <copy file="${src.dir}/welcome.xhtml" todir="${tmp.dir}"/>
           <copy file="${src.dir}/ApplicationMessages.properties" todir="${tmp.dir}/WEB-INF/classes"/>
           <copy file="${src.dir}/HelloBean.java" todir="${tmp.dir}/WEB-INF/classes"/>
           <copy file="${src.dir}/web.xml" todir="${tmp.dir}/WEB-INF"/>
           <copy file="${src.dir}/faces-config.xml" todir="${tmp.dir}/WEB-INF"/>
           <jar jarfile="${tmp.dir}/${war.name}" basedir="${tmp.dir}" compress="true" />
           <copy file="${tmp.dir}/${war.name}" tofile="${output.dir}/${war.name}"/>

           <delete includeEmptyDirs="true">
              <fileset dir="${tmp.dir}"/>

        <target name="deploy" depends="build">
            <echo message="*******************  Deploying the WAR file ${war.name} *********************" />  
            <echo message="********** ${output.dir}/${war.name} to ${jboss.home}/standalone/deployments **********" />  
            <copy todir="${jboss.home}/standalone/deployments/">
                <fileset dir="${output.dir}/">
                  <include name="${war.name}"/> 
            <echo message="*******************  Deployed Successfully   *********************" />  
            <echo message="http://localhost:8080/${war.context}" />

NOTE: The only change in the above file you need to do is to change the “jboss.home” directory path in the second line of the above script to point to your own JBoss AS7 directory.

Step11). Now before running your ANT script to build and deploy the above webapplication you should have the ANT as well as JAVA set in the $PATH variable of the Shell / command prompt as following:

For Unix Based OS:
export PATH=/home/userone/jdk1.6.0_21/bin:/home/userone/org.apache.ant_1.6.5/bin:$PATH

For Windows Based OS:
set PATH=C:/jdk1.6.0_21/bin;C:/org.apache.ant_1.6.5/bin;%PATH%

Step12). Now once the PATH is set In the command/Shell prompt you can move inside the directory “/home/userone/JSF2_BeanValidation_Demo” and then run the ant to build the webservice. by running the command “ant deploy”

[userone@localhost JSF2_BeanValidation_Demo]$ ant deploy
Buildfile: /home/userone/JSF2_BeanValidation_Demo/build.xml

   [delete] Deleting directory /home/userone/JSF2_BeanValidation_Demo/build
    [mkdir] Created dir: /home/userone/JSF2_BeanValidation_Demo/build
    [mkdir] Created dir: /home/userone/JSF2_BeanValidation_Demo/tmp

    [mkdir] Created dir: /home/userone/JSF2_BeanValidation_Demo/tmp/WEB-INF/classes
    [javac] Compiling 3 source files to /home/userone/JSF2_BeanValidation_Demo/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/JSF2_BeanValidation_Demo/tmp
     [copy] Copying 1 file to /home/userone/JSF2_BeanValidation_Demo/tmp
     [copy] Copying 1 file to /home/userone/JSF2_BeanValidation_Demo/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/JSF2_BeanValidation_Demo/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/JSF2_BeanValidation_Demo/tmp/WEB-INF
     [copy] Copying 1 file to /home/userone/JSF2_BeanValidation_Demo/tmp/WEB-INF
      [jar] Building jar: /home/userone/JSF2_BeanValidation_Demo/tmp/EE6_BeanValidationDemo.war
     [copy] Copying 1 file to /home/userone/JSF2_BeanValidation_Demo/build

     [echo] *******************  Deploying the WAR file EE6_BeanValidationDemo.war *********************
     [echo] ********** build/EE6_BeanValidationDemo.war to /home/userone/jboss-as-7.1.0.CR1b/standalone/deployments **********
     [copy] Copying 1 file to /home/userone/jboss-as-7.1.0.CR1b/standalone/deployments
     [echo] *******************  Deployed Successfully   *********************
     [echo] http://localhost:8080/EE6_BeanValidationDemo

Total time: 3 seconds

Step13). Now access the WebApplication like following :

You will notice that the Bean Validation is working as following:

BeanValidation JSR-303 EE6 feature in JBoss

Thanks 🙂
Middleware Magic Team