This article was first published on Java Advent Calendar.
Introduction to Bean Validation
JavaBeans Validation (Bean 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.
Several built-in constraints are available in the javax.validation.constraints package. The Java EE 6 Tutorial lists all the built-in constraints.
Constraints in Bean Validation are expressed via Java annotations:
public class Person {
@NotNull
@Size(min = 2, max = 50)
private String name;
// ...
}
Bean Validation and RESTful web services
JAX-RS 1.0 provides great support for extracting request values and binding them into Java fields, properties and parameters using annotations such as @HeaderParam, @QueryParam, etc. It also supports binding of request entity bodies into Java objects via non-annotated parameters (i.e., parameters that are not annotated with any of the JAX-RS annotations). Currently, any additional validation on these values in a resource class must be performed programmatically.
The next release, JAX-RS 2.0, includes a proposal to enable validation annotations to be combined with JAX-RS annotations. For example, given the validation annotation @Pattern, the following example shows how form parameters could be validated.
» Read more: Integrating Bean Validation with JAX-RS in Java EE 6