ValidationFeaturePage edited by Andrew RedkoChanges (5)
Full ContentBean Validation Feature
IntroductionBean Validation 1.1 (JSR-349), an evolution of Bean Validation 1.0 (JSR-303), introduces a very powerful concepts of declarative constraints (based on Java annotations) to define the expectation for:
Here are couple of typical examples:
public class Person {
@NotNull private String firstName;
@NotNull private String lastName;
@Valid @NotNull private Person boss;
public @NotNull String saveItem( @Valid @NotNull Person person, @Max( 23 ) BigDecimal age ) {
// ...
}
}
Bean Validation API has been part of JPA 2.0 (JSR-317) and has proven to be successful and very useful, helping developers to delegate routine validation tasks to solid, very extensible framework. It is very easy to create own constraints, including complex cross-field ones. DependenciesBean Validation support in Apache CXF is implementation-independent and is built solely using API. As such, the only required dependency is: <dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
API doesn't provide implementation but there are couple of choices to pick from. Please notice that bean validation implementation is taken from the ones present in classpath. If no implementation is detected, bean validation is not available for use and constraints validation won't have any effect. Using Hibernate Validator as bean validation providerhttp://www.hibernate.org/subprojects/validator.html Hibernate Validator is mature and feature-rich validation provider with full support of Bean Validation 1.1 (as of version 5.x.x which is the reference implementation for JSR 349 - Bean Validation 1.1 API). To use Hibernate Validator in your Apache CXF projects, couple of additional dependencies should be included: <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0-b02</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0-b01/version>
</dependency>
Hibernate Validator uses Java _expression_ Language 3.0 in order to provide better validation messages support so the respective EL 3.0 API and implementation dependencies should be included. Using Apache BVal as bean validation providerCurrent stable version of Apache BVal (0.5) doesn't support Bean Validation 1.1 but the upcoming 1.1.0 should have it fully implemented (at the moment 1.1.0-alpha-SNAPSHOT could be used). <dependency>
<groupId>org.apache.bval</groupId>
<artifactId>bval-jsr</artifactId>
<version>1.1.0-alpha-SNAPSHOT</version>
</dependency>
Common Bean Validation 1.1 InterceptorsGeneric Bean Validation 1.1 implementation is build around two interceptors and validation provider:
Feature-specific implementation for JAX-RS / JAX-WS is built on top of these common blocks. Bean Validation 1.1 and JAX-RS 2.0 integrationJAX-RS 2.0 and Bean Validation 1.1Among many other features, JAX-RS 2.0 specification introduces Bean Validation 1.1 support as a mandatory part of implementation. In an effort to fulfill this requirement, Apache CXF provides full-fledge validation support for JAX-RS / JAX-WS endpoints, both for request parameters and response values. Bean Validation 1.1 support in JAX-RS 2.0 is built on top of three main components:
All these components may share the single instance of org.apache.cxf.validation.BeanValidationProvider which actually delegates all validation logic to available Bean Validation 1.1 implementation. Configuring Bean Validation 1.1 using JAXRSServerFactoryBeanIt's quite easy to enable bean validation support using JAXRSServerFactoryBean as following code snippet shows: JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean(); sf.setResourceClasses( ... ); sf.setResourceProvider( ... ); sf.setProvider(new ValidationExceptionMapper()); sf.setInInterceptors(Arrays.< Interceptor< ? extends Message > >asList(new new JAXRSBeanValidationInInterceptor())); sf.setOutInterceptors(Arrays.< Interceptor< ? extends Message > >asList(new JAXRSBeanValidationOutInterceptor())); sf.create(); Configuring Bean Validation 1.1 using Spring bean definitions XMLFollowing the similar approach as for JAXRSServerFactoryBean, in case of Spring respective bean definitions should be added under <jaxrs:outInterceptors>, <jaxrs:inInterceptors> and <jaxrs:providers> sections, f.e.:
<jaxrs:server address="/">
<jaxrs:inInterceptors>
<ref bean="validationInInterceptor" />
</jaxrs:inInterceptors>
<jaxrs:outInterceptors>
<ref bean="validationOutInterceptor" />
</jaxrs:outInterceptors>
<jaxrs:serviceBeans>
...
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="exceptionMapper"/>
</jaxrs:providers>
</jaxrs:server>
<bean id="exceptionMapper" class="org.apache.cxf.jaxrs.validation.ValidationExceptionMapper"/>
<bean id="validationProvider" class="org.apache.cxf.validation.BeanValidationProvider" />
<bean id="validationInInterceptor" class="org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInInterceptor">
<property name="provider" ref="validationProvider" />
</bean>
<bean id="validationOutInterceptor" class="org.apache.cxf.jaxrs.validation.JAXRSBeanValidationOutInterceptor">
<property name="provider" ref="validationProvider" />
</bean>
Validation Exceptions and HTTP status codesAs per JAX-RS 2.0 specification, any input parameter validation violation is mapped to HTTP status code 400 Bad Request and any return value validation violation (or internal validation violation) is mapped to HTTP status code 500 Internal Server Error. This is essentially what org.apache.cxf.jaxrs.validation.ValidationExceptionMapper does.
ExamplesYou can use any predefined validation annotation as well as define your own as far as it follows Bean Validation 1.1 specification. This section includes couple of typical scenarios. Validating simple input parameters
@POST
@Path("/books")
public Response addBook(
@NotNull @Pattern(regexp = "\\d+") @FormParam("id") String id,
@NotNull @Size(min = 1, max = 50) @FormParam("name") String name) {
// ...
}
Validating complex input parameters
@POST
@Path("/books")
public Response addBook( @Valid Book book ) {
// ...
}
This example assumes that class Book has validation constraints defined, f.e.:
public class Book {
@NotNull @Pattern(regexp = "\\d+") private String id;
@NotNull @Size(min = 1, max = 50) private String name;
// ...
}
Validating return values (non-Response)
@GET
@Path("/books/{bookId}")
@Override
@NotNull @Valid
public Book getBook(@PathParam("bookId") String id) {
// ...
}
This example assumes that class Book has validation constraints defined (as in example above). Validating return values (Response)Returning Response object stands aside from all other usage scenarios. Usually, Response is a holder for another object (entity) but because Response has no validation constraints defined, the inner object (entity) is not validatable even if it has full set of validation constraints . Unfortunately, this particular use case is not described in JAX-RS 2.0 specification. Nevertheless, Apache CXF team thinks that such a validation would be beneficial and performs a simple trick: whenever Response is being returned, all defined for it validation constraints will be applied not to Response instance itself but to the entity it holds.
@GET
@Path("/books/{bookId}")
@Valid @NotNull
public Response getBookResponse(@PathParam("bookId") String id) {
return Response.ok( new Book( id ) ).build();
}
Stop watching space
|
Change email notification preferences
View Online
|
View Changes
|
- [CONF] Apache CXF Documentation > Validat... Sergey Beryozkin (Confluence)
- [CONF] Apache CXF Documentation > Va... Andrew Redko (Confluence)
- [CONF] Apache CXF Documentation > Va... Andrew Redko (Confluence)
- [CONF] Apache CXF Documentation > Va... Andrew Redko (Confluence)
- [CONF] Apache CXF Documentation > Va... Andrew Redko (Confluence)
- [CONF] Apache CXF Documentation > Va... Andrew Redko (Confluence)
- [CONF] Apache CXF Documentation > Va... Andrew Redko (Confluence)
- [CONF] Apache CXF Documentation > Va... Andrew Redko (Confluence)
- [CONF] Apache CXF Documentation > Va... Andrew Redko (Confluence)
- [CONF] Apache CXF Documentation > Va... Andrew Redko (Confluence)
- [CONF] Apache CXF Documentation > Va... Andrew Redko (Confluence)
- [CONF] Apache CXF Documentation > Va... Daniel Kulp (Confluence)
