Apache CXF
Apache CXF Documentation > Index > RESTful Services > JAX-RS Download | Documentation
Overview
How-Tos
Frontends
DataBindings
Transports
Configuration
Debugging and Logging
Tools
RESTful Services
WSDL Bindings
Service Routing
Dynamic Languages
WS-* Support
Advanced Integration
Deployment
Use of Schemas and Namespaces
--------------------------------------------------------------------------------
API (Javadoc)
CXF Website
JAX-RS (JSR-311)
Introduction
Migrating from 0.8 to 1.0
Maven dependencies
Setting up the classpath in Eclipse or Ant
CXF JAX-RS bundle
Understanding the basics
Resource class
@Path
HTTP Method
Return types
Exception handling
Dealing with Parameters
Parameter beans
Resource lifecycles
Overview of the selection algorithm.
Selecting between multiple resource classes
Selecting between multiple resource methods
Resource methods and media types
Custom selection between multiple resources
Context annotations
URIs calculation using UriInfo and UriBuilder
Annotation inheritance
Sub-resource locators.
Static resolution of subresources
Message Body Providers
Custom Message Body Providers
Registering custom providers
Customizing media types for message body providers
Support for data bindings
JAXB support
Configuring JAXB provider
JSON support
Configuring JSON provider
Dealing with JSON array serialization issues
BadgerFish convention
Wrapping and Unwrapping JSON sequences
Automatic JAXBElement conversion during serialization
Handling JAXB beans without XmlRootElement annotations
Handling explicit collections
Customizing JAXB XML and JSON input and output
Aegis Data Binding
XMLBeans
Support for CXF DataBindings
Schema validation support
Debugging
Logging
ATOM push-style logging
Spring configuration
Properties file
Programming style
Filters
Difference between JAXRS filters and CXF interceptors
Overriding request and response properties
Overriding HTTP method
Overriding request URI
Overriding response status code and headers
Ignoring JAXRS MessageBodyWriters
Custom invokers
Advanced HTTP
Support for Continuations
Secure JAX-RS services
Checking HTTP security headers
SecurityManager and IllegalAccessExceptions
Client API
Proxy-based API
Customizing proxies
Converting proxies to Web Clients and vice versa
Handling exceptions
Configuring proxies in Spring
Injecting proxies
Limitations
HTTP-centric clients
Handling exceptions
Configuring HTTP clients in Spring
XML-centric clients
Configuring Clients at Runtime
Configuring HTTP Conduit from Spring
XPath and XSLT
XPath support
XSLT support
Redirection
With RequestDispatcherProvider
With CXFServlet
Custom Redirection
Model-View-Controller support
XSLT
JSP
Support for Multiparts
Reading attachments
Forms and multiparts
Writing attachments
Uploading files
Reading large attachments
Service listings and WADL support
Documenting resource classes and methods in WADL
Configuring JAX-RS services
Configuring JAX-RS services programmatically can create a JAX-RS RESTful service by using JAXRSServerFactoryBean from the cxf-rt-frontend-jaxrs package:
Configuring JAX-RS endpoints programmatically without Spring
Configuring JAX-RS clients programmatically without Spring
Configuring JAX-RS services in container with Spring configuration file.
web.xml
Using Spring ContextLoaderListener
Using CXFServlet init parameters
beans.xml
Configuring JAX-RS services in container without Spring
Attaching JAXRS endpoints to an existing Jetty server
Configuring JAX-RS services programmatically with Spring configuration file.
Lifecycle management
From Spring
With CXFNonSpringJaxrsServlet
Programmatically
PostConstruct and PreDestroy
Locating custom resources in web applications
Multiple endpoints and resource classes
How the request URI is matched against a given jaxrs endpoint
Combining JAX-WS and JAX-RS
Dealing with contexts
JAX-RS and Spring AOP
RESTful services without annotations
Configuration
Integration with Distributed OSGi
How to contribute
Introduction
CXF supports JAX-RS (JSR-311), Java API for RESTful Web Services. JAX-RS provides a more standard way to build RESTful services in Java. CXF 2.2.x supports the final version of JSR-311 API while CXF 2.1.x supports the 0.8 version of JSR-311 API .
JAX-RS related demos are located under samples/jax_rs directory (CXF 2.2 and CXF 2.1 only).
This documentation will refer to JSR-311 API 1.0 .
Migrating from 0.8 to 1.0
The following major changes in 1.0 will most likely affect users migrating from 0.8
@ProduceMime and @ConsumeMime have been replaced with @Produces and @Consumes respectively
HttpHeaders has had some of its methods returning a string representation of Locale updated to return Locale instead
As JAX-RS API 1.0 is currently supported in CXF 2.2.x, it's also worth noting of the following changes in dependencies :
Spring version have changed from 2.0.8 in 2.1.x to 2.5.6
jaxb-api version has changed to javax.xml.bind/jaxb-api/2.1
jaxb-impl version has changed to com.sun.xml.bind/jaxb-impl/2.1.7
Additionally, org.apache.cxf/cxf-rt-databinding-aegis/2.2.x compile-time dependency has been added
Maven dependencies
To incorporate JAX-RS, you will need:
org.apache.cxf
cxf-rt-frontend-jaxrs
2.2.3
This will in turn pull in the following 3rd-party dependencies are used when building CXF JAX-RS implementation :
1. javax.ws.rs/jsr311-api/1.0
available from either
java.net.2
Java Net 2 Repository
http://download.java.net/maven/2
or from a central maven repository
2. org.apache.abdera groupId : abdera-core, abdera-parser and abdera-extensions-json artifacts, version 0.4.0-incubating. It's a compile time dependency. Available from
apache.incubating
Apache Incubating Repository
http://people.apache.org/repo/m2-incubating-repository
3. org.springframework/spring-core/2.5.6
4. org.codehaus.jettison/jettison/1.1
5. org.apache.xmlbeans/xmlbeans/2.3.0 - compile time
Please check the pom.xml for the list of cxf components used by the JAX-RS implementation. Snapshots are available from http://repository.apache.org/snapshots/org/apache/cxf/apache-cxf/
Setting up the classpath in Eclipse or Ant
If no Maven is used then the following jars need to be available at the runtime classpath :
cxf-2.3.0-SNAPSHOT.jar
jsr311-api-1.0.jar
jaxb-impl-2.1.12.jar
jaxb-api-2.1.jar
geronimo-annotation_1.0_spec-1.1.1.jar
geronimo-activation_1.1_spec-1.0.2.jar
geronimo-servlet_2.5_spec-1.2.jar
commons-logging-1.1.1.jar
geronimo-stax_api_1.0_spec-1.0.1.jar
woodstox-core-asl-4.0.3.jar
stax2-api-3.0.1.jar
geronimo-jaxws_2.1_spec-1.0.jar
wsdl4j-1.6.2.jar
XmlSchema-1.4.5.jar
neethi-2.0.4.jar
For CXF 2.2.3 (2.2.4-SNAPSHOT) :
add cxf-2.2.3.jar (or cxf-2.2.4-SNAPSHOT.jar) instead of cxf-2.3.0-SNAPSHOT.jar
do not add stax2-api-3.0.1.jar
add wstx-asl-3.2.8.jar instead of woodstox-core-asl-4.0.3.jar
add saaj-api-1.3.jar
If Spring configuration is used then add spring.jar from the Spring distribution or the spring jars available in the CXF distribution. When creating client proxies from concrete classes the cglib-nodep-2.1_3.jar needs to be added. You do not need to add JAXB libraries if you do not use JAXB. If you depend on Jetty then you will also need to add two jetty jars shipped with CXF.
We will work on reducing the set of required dependencies.
Please see the configuration sections below on how a spring dependency can be dropped.
CXF JAX-RS bundle
A standalone JAX-RS bundle is now available which may be of interest to users doing JAX-RS work only.
Understanding the basics
You are encouraged to read JAX-RS spec to find out information not covered by this documentation.
Resource class
A resource class is a Java class annotated with JAX-RS annotations to represent a Web resource. Two types of resource classes are available : root resource classes and subresource classes. A root resource class is annotated at least with a @Path annotation, while subresource classes typically have no root @Path values. A typical root resource class in JAX-RS looks like this below:
package demo.jaxrs.server;
java.util.HashMap;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
@Path("/customerservice/")
@Produces("application/xml")
public class CustomerService {
public CustomerService() {
}
@GET
public Customers getCustomers() {
......
}
@GET
@Path("/customers/{id}")
@Produces("application/json")
public Customer getCustomer(@PathParam("id") String id) {
......
}
@PUT
@Path("/customers/{id}")
@Consumes("application/xml")
public Response updateCustomer(@PathParam("id") Long id, Customer customer) {
......
}
@POST
@Path("/customers")
public Response addCustomer(Customer customer) {
......
}
@DELETE
@Path("/customers/{id}/")
public Response deleteCustomer(@PathParam("id") String id) {
......
}
@Path("/orders/{orderId}/")
public Order getOrder(@PathParam("orderId") String orderId) {
......
}
}
Customer resource class can handle requests starting from /customerservice. When /customerservice request is matched to this class, its getCustomers() method will be selected. updateCustomer(), deleteCustomer() and addCustomer() are used to serve POST, PUT and DELETE requests starting from /customerservice/customer, while getOrder() method delegates the handling of requests like /customerservice/orders/1 to a subresource locator Order.
@Produces annotation is used to specify the format of the response. When not available on the resource method, it's inherited from a class, and if it's not available on the class then it's inherited from a corresponding message body writer, if any. Default value is */*, but it's recommended that some definite value is specified. The same applies to @Consumes, only it's message body readers that are checked as the last resort.
For example, getCustomers() method inherits @Produces annotation from its class, while getCustomer() method overrides it with its own value.
@Path
@Path annotation is applied to resource classes or methods. The value of @Path annotation is a relative URI path and follows the URI Template format and may include arbitrary regular expressions. When not available on the resource method, it's inherited from a class. For example :
@Path("/customers/{id}")
public class CustomerResource {
@GET
public Customer getCustomer(@PathParam("id") Long id) {
......
}
@GET
@Path("/order/{orderid}")
public Order getOrder(@PathParam("id") Long customerId, @PathParam("orderid") Long orderId) {
......
}
@GET
@Path("/order/{orderid}/{search:.*}")
public Item findItem(@PathParam("id") Long customerId,
@PathParam("orderid") Long orderId,
@PathParam("search") String searchString,
@PathParam("search") List
searchList) {
......
}
}
This example is similar to the one above it, but it also shows that an {id} template variable specified as part of the root @Path expression is reused by resource methods and a custom regular expression is specified by a findItem() method (note that a variable name is separated by ':' from an actual expression).
In this example, a request like 'GET /customers/1/order/2/price/2000/weight/2' will be served by the findItem() method.
List can be used to get to all the path segments in 'price/2000/weight/2' captured by the regular expression.
More information about Path annotations can be found from JAX-RS spec section 2.3.
HTTP Method
JAX-RS specification defines a number of annotations such as @GET, @PUT, @POST and @DELETE. Using an @HttpMethod designator, one can create a custom annotation such as @Update or @Patch. For example :
package org.apache.cxf.customverb;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("PATCH")
public @interface PATCH {
}
Return types
Either javax.ws.rs.core.Response or custom type can be returned. javax.ws.rs.core.Response can be used to set the HTTP response code, headers and entity. JAX-RS MessageBodyWriters (see below) are in charge of serializing the response entities, those which are returned directly or as part of javax.ws.rs.core.Response.
Exception handling
One can either throw an unchecked WebApplicationException or return Response with a proper error code set.
The former option may be a better one when no JAX-RS types can be added to method signatures.
For example :
@Path("/customerservice/")
public class CustomerService {
@PUT
@Path("/customers/{id}")
public Response updateCustomer(@PathParam("id") Long id, Customer customer) {
return Response.status(errorCode).build();
}
@POST
@Path("/customers")
public Customer addCustomer(Customer customer) {
throw new WebApplicationException(errorCode);
}
}
Yet another option is to register an ExceptionMapper provider. Ex :
public BookExceptionMapper implements ExceptionMapper {
public Response toResponse(BookException ex) {
// convert to Response
}
}
This allows to throw a checked or runtime exception from an application code and map it to an HTTP response in a registered provider.
Have a look please at this exception mapper which converts Spring Security exceptions into HTTP 403 error code for another example.
Note that when no mappers are found for custom exceptions, they are propogated (wrapped in ServletException) to the underlying container as required by the specification. Thus one option for intercepting the exceptions is to register a custom servlet filter which will catch ServletExceptions and handle the causes. If no custom servlet filter which can handle ServletExceptions is available then most likely only 500 error status will be reported.
This propogation can be disabled by registering a boolean jaxrs property 'org.apache.cxf.propogate.exception' with a false value. If such property is set and no exception mapper can be found for a given exception then it will be wrapped into an xml error response by the CXF XMLFaultOutInterceptor.
One can also register a custom CXF out fault interceptor which can handle all the exceptions by writing directly to the HttpServletResponse stream or XMLStreamWriter (as XMLFaultOutInterceptor does). For example, see this test interceptor.
Dealing with Parameters
PathParam annotation is used to map a given Path template variable to a method parameter.
For example :
@Path("/customer/{id}")
public class CustomerService {
@PUT
@Path("{name}")
public Response updateCustomer(@PathParam("id") Long id, @PathParam("name") String name) {
...
}
}
In this case a template variable id available from a root class annotation is mapped to a parameter of type Long, while a name variable is mapped to a parameter of type String.
@QueryParam, @HttpHeader, @MatrixParam, @FormParam and @CookieParam annotations are also supported.
Parameters can be of type String or of any type that have constructors accepting a String parameter or static valueOf(String s) methods.
Additionally CXF JAXRS checks for static fromString(String s) method, so types with no valueOf(String) factory methods can also be dealt with :
public enum Gender {
MALE,
FEMALE;
public static fromString(String s) {
if ("1".equals(s)) {
return FEMALE;
} else if ("1".equals(s)) {
return MALE;
}
return valueOf(s);
}
}
@Path("/{g}")
public class Service {
@PUT
@Path("{id}")
public Response update(@PathParam("g") Gender g, @PathParam("id") UUID u) {
...
}
}
Note that on the trunk enums with fromValue() factory methods are also supported.
JAX-RS PathSegment is also supported. A sequence of identically named parameters (queries, headers, etc) can be mapped to List or Set or SortedSet.
CXF JAXRS supports ParameterHandler extensions which can be used to deal with method parameters annotated with one of the JAXRS parameter annotations :
public class MapHandler implements ParameterHandler