Integrate ZK with JSR 303: Bean Validation

From Documentation
DocumentationSmall Talks2011MayIntegrate ZK with JSR 303: Bean Validation
Integrate ZK with JSR 303: Bean Validation

Simon Pai, Engineer, Potix Corporation
May 20, 2011
ZK 5.0.7

What is JSR 303: Bean Validation

JSR 303 is a standard designed for working on property validation in Java beans. In brief, the constraints of a bean property are specified by Java annotations, and validation against the bean can be invoked by API.

A known implementation of JSR 303 is Hibernate Validator. In the following section we will use Hibernate Validator to demonstrate how to utilize this tool in a ZK application.


How to use Bean Validation

The usage of this tool is quite straightforward: You just need to specify property constraints and invoke validation.


public class User {
	@NotEmpty(message = "Last name can not be null.")
	private String _lastName;
	@Past(message = "Birth date must be in the past.")
	private Date _birthDate;

Invoke Validation

// prepare for Validator
ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
Validator validator = vf.getValidator();

// suppose we have a bean of User like this:
User user = new User();
user.setLastName(""); // wrong, should not be empty

// invoke validation, which will return a set of violations to the constraints
Set<ConstraintViolation<User>> violations = validator.validate(user);
for(ConstraintViolation<User> v : violations)
	System.out.println(v.getMessage()); // will print out: "Last name can not be null."


How to use Bean Validation in your ZK application

The following is a step-by-step guide to show a simple integration of JSR 303 with data binding.

Required Jars

The following is a sample dependency list for setting up Hibernate Validator to work with data binding:

	<!-- required for data binding -->

Hibernate Validator assumes the use of log4j to log information. You can use any log4j implementation you prefer.



Under project classpath, you need to prepare

  2. META-INF/validation.xml

Here are examples of minimal settings in these files:

log4j.rootLogger=info, stdout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n


<?xml version="1.0" encoding="UTF-8"?>

You can customize the setting depending on your requirement.


Working with data binding

Upon the validation phase of data binding, you can use the JSR 303 Validator to verify the value against the constraints. Note that the constraints are specified on getter methods to work with data binding.

For example:

public class User {
	private String _firstName;
	private String _lastName;
	private Date _birthDate;
	// getter, setter //
	@NotEmpty(message = "First name can not be null")
	public String getFirstName() {
		return _firstName;
	public void setFirstName(String name) {
		_firstName = name;
	@NotEmpty(message = "Last name can not be null")
	public String getLastName() {
		return _lastName;
	public void setLastName(String name) {
		_lastName = name;
	@Past(message = "Birth date must be in the past")
	public Date getBirthDate() {
		return _birthDate;
	public void setBirthDate(Date date) {
		_birthDate = date;


<?page title="Bean Validation" ?>
<?init class="org.zkoss.zkplus.databind.AnnotateDataBinderInit" ?>
	<window id="win" apply="org.zkoss.demo.DemoController">
		<grid width="300px">
				<column width="100px" />
				<column width="200px" />
					First Name
					<textbox id="firstNameBox" value="@{win$composer.user.firstName, save-when='submit.onClick'}" />
					Last Name
					<textbox id="lastNameBox" value="@{win$composer.user.lastName, save-when='submit.onClick'}" />
					Birth Date
					<datebox id="birthDateBox" value="@{win$composer.user.birthDate, save-when='submit.onClick'}" />
		<button id="submit" label="Submit" />

public class DemoController extends GenericForwardComposer {
	public User getUser() {
		return User.getUser();
	public void onBindingValidate$submit(BindingValidateEvent event) {
		Validations.validate(event, null);


public class Validations {
	private static final Validator _validator = Validation.buildDefaultValidatorFactory().getValidator();
	public static void validate(BindingValidateEvent event, ViolationRunner runner) {
		Iterator<Component> refs = event.getReferences().iterator();
		Iterator<Binding> bindings = event.getBindings().iterator();
		Iterator<?> values = event.getValues().iterator();
		List<WrongValueException> wvelist = new ArrayList<WrongValueException>();
		while(refs.hasNext() && bindings.hasNext() && values.hasNext()) {
			Component ref =;
			Binding binding =;
			Object value =;
			Object bean = binding.getBean(ref);
			String expr = binding.getExpression();
			String propName = expr.substring(expr.lastIndexOf('.') + 1);
			Set<ConstraintViolation<?>> vs = validate(bean.getClass(), propName, value);
			// collect WrongValueException
			for(ConstraintViolation<?> v : vs)
				wvelist.add(new WrongValueException(ref, v.getMessage()));
			// call runner
			if(runner != null), bean, ref);
		// this will interrupt binding value to bean, so bean is not modified
			throw new WrongValuesException(wvelist.toArray(new WrongValueException[0]));
	// interface //
	public interface ViolationRunner {
		public void run(Set<ConstraintViolation<?>> violations, Object bean, Component ref);
	// helper //
	private static Set validate(Class clazz, String propName, Object value) {
		return _validator.validateValue(clazz, propName, value);







Copyright © Potix Corporation. This article is licensed under GNU Free Documentation License.