JAX-RS (JSR-311)
Introduction
JAX-RS: Java API for RESTful Web Services is a Java programming language API that provides support in creating web services according to the Representational State Transfer (REST) architectural style.
CXF supports JAX-RS (JSR-311), the Java API for RESTful Web Services. JAX-RS standardizes the way RESTful services can be developed in Java.
CXF 2.5.x, 2.4.x and 2.3.x supports JSR-311 API 1.1 and is JAX-RS TCK 1.1 compliant.
The JAX-RS 1.1 specification may be found here
CXF 2.2.x supports JSR-311 API 1.0 and is JAX-RS TCK 1.0. compliant.
The JAX-RS 1.0 specification may be found here
CXF 2.1.x supports JSR-311 API 0.8.
JAX-RS related demos are located under the samples/jax_rs directory.
This documentation will refer to JSR-311 API 1.1.
Outstanding JAX-RS JIRA issues can be found here.
Project setup and configuration
Migration
Migrating from 1.0 to 1.1
Existing JAX-RS 1.0 applications should run in CXF 2.4.x without any problems.
There have been just a few minor modifications at the JAX-RS API level:
- The
@ApplicationPath
annotation has been added for JAX-RS Application subclasses - The
Request
interface has been updated with a new no-argumentevaluatePreconditions
method - existing applications which are already using theRequest
interface may need to be recompiled
Maven dependencies
To incorporate JAX-RS, you will need:
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxrs</artifactId> <version>2.4.0</version> </dependency>
This will in turn pull in other CXF modules such cxf-api
, cxf-rt-core
, cxf-rt-transports-http
and cxf-rt-bindings-xml
as well as the following 3rd-party dependencies:
1. javax.ws.rs/jsr311-api/1.1.1
(or 1.0 for CXF 2.2.x)
2. org.apache.abdera groupId: abdera-core, abdera-parser and abdera-extensions-json artifacts, version 1.1. Note that starting from CXF 2.3.0 the Abdera dependencies are optional.
3. org.springframework/spring-core/3.0.5-RELEASE
(and other core Spring dependencies)
4. org.codehaus.jettison/jettison/1.3
Note that starting from CXF 2.3.2 and 2.4.0 the cxf-rt-databindings-aegis
and org.apache.xmlbeans/xmlbeans/2.4.0
dependencies are optional. If you are not working with the CXF distributions containing these dependencies but using Maven to pull in either the CXF JAX-RS Bundle or the cxf-rt-frontend-jaxrs
frontend then please make sure one of the following dependencies is also included as needed :
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-databinding-aegis</artifactId> <!-- 2.3.4 or 2.4.0 --> <version>${cxf.version}</version> </dependency> <dependency> <groupId>org.apache.xmlbeans</groupId> <artifactId>xmlbeans</artifactId> <version>2.4.0</version> </dependency>
Starting from CXF 2.4.0 the wsdl4j transitive dependency is only required for running the CXF JAX-RS client code due to one of the HTTP transport extensions indirectly depending on wsdl4j. When running the server endpoints only, you can add the wsdl4j exclusion to either cxf-frontend-jaxrs or cxf-bundle-jaxrs dependency:
<exclusion> <groupId>wsdl4j</groupId> <artifactId>wsdl4j</artifactId> </exclusion>
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
If Maven is not used then the following JARs will need to be available at the runtime classpath.
For CXF 2.4.1:
- cxf-2.4.1.jar
- jsr311-api-1.1.1.jar
- jaxb-impl-2.1.13.jar
- jaxb-api-2.1.jar
- geronimo-annotation_1.0_spec-1.1.1.jar
- geronimo-activation_1.1_spec-1.1.jar
- geronimo-servlet_3.0_spec_1.0.jar
- commons-logging-1.1.1.jar
- geronimo-stax_api_1.0_spec-1.0.1.jar
- woodstox-core-asl-4.0.8.jar
- stax2-api-3.0.1.jar
- wsdl4j-1.6.2.jar (only needed at the client side)
- xmlschema-core-2.0.jar
- neethi-3.0.0.jar
For CXF 2.3.5:
- cxf-2.3.5.jar
- jsr311-api-1.1.1.jar
- jaxb-impl-2.1.13.jar
- jaxb-api-2.1.jar
- geronimo-annotation_1.0_spec-1.1.1.jar
- geronimo-activation_1.1_spec-1.1.jar
- geronimo-servlet_3.0_spec_1.0.jar
- commons-logging-1.1.1.jar
- geronimo-stax_api_1.0_spec-1.0.1.jar
- woodstox-core-asl-4.0.8.jar
- stax2-api-3.0.1.jar
- wsdl4j-1.6.2.jar
- XmlSchema-1.4.5.jar
- neethi-2.0.4.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 Jetty 7 or Jetty 6 JARs shipped with CXF.
We are working on reducing the set of required dependencies.
Please see the configuration sections below on how the 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 the JAX-RS work only.
Please note that this bundle has a transitive Maven dependency on the Jetty server modules. If you are using Maven and working with other servlet containers such as Tomcat then please add the following exclusion:
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-bundle-jaxrs</artifactId> <!-- 2.3.5 or 2.4.1 --> <version>${cxf.version}</version> <exclusions> <exclusion> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-server</artifactId> </exclusion> </exclusions> </dependency>
What is New
- New TransformationFeature can be used for manipulating in and out XML and JSON payloads. This feature can be used instead of explicitly configuring default JAXB and JSON providers.
- Initial support for WADL-first development, please see WADL section for more information.
- Failover and Load Distribution support for CXF JAX-RS clients, please see Failover section for more information.
Getting Started with JAX-RS
Understanding the Basics
You are encouraged to read JAX-RS spec (html version) to find out information not covered by this documentation. The specification introduces many terms such as root resources, resource methods, sub-resources and sub-resource locators, message body readers and writers.
Please see the JAX-RS Basics page for more information.
Support for Data Bindings
JAX-RS MessageBodyReader and MessageBodyWriter can be used to create data bindings for reading and writing data in a number of different formats. Compliant JAX-RS implementations are expected to support JAXB-annotated beans, JAXP Source objects, InputStreams, etc.
In addition, CXF JAX-RS lets users reuse existing CXF DataBindings for working with JAXB, XBeans, Aegis and SDO.
Please see the JAX-RS Data Bindings page for more information.
How Request URI is Matched
Lets assume you have a web application called 'rest'. CXFServlet's url-pattern is "/test/*". Finally, jaxrs:server's address is "/bar".
Requests like /rest/test/bar or /rest/test/bar/baz will be delivered to one of the resource classes in a given jaxrs:server endpoint. For the former request to be handled, a resource class with @Path("/") should be available, in the latter case - at least @Path("/") or a more specific @Path("/baz").
The same requirement can be expressed by having a CXFServlet with "/*" and jaxrs:server with "/test/bar".
When both CXFServlet and jaxrs:server use "/" then it's a root resource class which should provide a @Path with at least "/test/bar" for the above requests to be matched.
Generally, it can be a good idea to specify the URI segments which are more likely to change now and then with CXFServlets or jaxrs:server.
Client API
JAX-RS 1.1 does not provide for a standard approach toward consuming pure HTTP-based services thus CXF JAX-RS provides a comprehensive support for developing RESTful clients by introducing 3 flavors of the client API: proxy-based, HTTP-centric and XML-centric.
Please see the JAX-RS Client API page for more information.
Filters, Interceptors and Invokers
It is possible to intercept and modify the inbound and outbound calls with the help of CXF JAX-RS filters and/or CXF interceptors. Additionally, custom invokers offer an option to intercept a call immediately before a service bean is invoked.
Please see the JAX-RS Filters page for more information.
Service listings and WADL support
CXF JAX-RS supports WADL. CXF JAX-RS service endpoints can be listed in the service listings page and users can check the WADL documents.
Please see the JAXRS Services Description page for more information.
Configuring JAX-RS services
JAX-RS services can be configured programmatically from Spring or using CXFNonSpringJAXRSServlet.
Please see the JAXRS Services Configuration page for more information.
Debugging
One may want to use a browser to test how a given HTTP resource reacts to different HTTP Accept or Accept-Language header values and request methods. For example, if a resource class supports a "/resource" URI then one can test the resource class using one of the following queries :
> GET /resource.xml
> GET /resource.en
The runtime will replace '.xml' or '.en' with an appropriate header value. For it to know the type or language value associated with a given URI suffix, some configuration needs to be done. Here's an example of how it can be done with Spring:
<jaxrs:server id="customerService" address="/"> <jaxrs:serviceBeans> <bean class="org.apache.cxf.jaxrs.systests.CustomerService" /> </jaxrs:serviceBeans> <jaxrs:extensionMappings> <entry key="json" value="application/json"/> <entry key="xml" value="application/xml"/> </jaxrs:extensionMappings> <jaxrs:languageMappings> <entry key="en" value="en-gb"/> </jaxrs:languageMappings> </jaxrs:server>
CXF also supports a _type query as an alternative to appending extensions like '.xml' to request URIs:
{{ > GET /resource?_type=xml}}
Overriding a request method is also easy:
> GET /resource?_method=POST
Alternatively, one can specify an HTTP header X-HTTP-Method-Override:
> POST /books
> X-HTTP-Method-Override : PATCH
For example, at the moment the http-centric client API does not support arbitrary HTTP verbs except for those supported
by Java HTTPUrlConnection. When needed, X-HTTP-Method-Override can be set to overcome this limitation.
Finally, a "_ctype" query allows for overriding Content-Type.
Please see the Debugging and Logging page for more information on how to debug and log service calls in CXF.
Logging
Many of the existing CXF features can be applied either to jaxrs:server
or jaxrs:client
. For example, to enable logging of requests and responses, simply do:
<beans xmlns:cxf="http://cxf.apache.org/core" xsi:schemaLocation="http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd"> <jaxrs:server> <jaxrs:features> <cxf:logging/> </jaxrs:features> <jaxrs:server> </beans>
Please make sure the http://cxf.apache.org/core
namespace is in scope.
Starting from CXF 2.3.0 it is also possible to convert log events into Atom entries and either push them to receivers or make them available for polling.
Please see the Debugging and Logging page for more information.
Advanced Features
Multiparts
Multiparts can be handled in a number of ways. The CXF core runtime provides advanced support for handling attachments which CXF JAX-RS builds upon.
Please see the JAX-RS Multiparts page for more information.
Secure JAX-RS services
Transport level HTTPS security can be used to protect messages exchanged between CXF JAX-RS endpoints and providers.
Authentication and authorization can be enforced in a number of ways.
Please see the Secure JAX-RS Services page for more information.
Please also check JAX-RS XML Security, JAX-RS SAML and JAX-RS OAuth pages for more information about the advanced security topics.
Failover and Load Distribution Features
Starting from CXF 2.4.1, CXF JAX-RS proxy and WebClient consumers can be backed up by failover and load distribution features.
Please see the JAX-RS Failover page for more information.
Redirection
Starting from CXF 2.2.5 it is possible to redirect the request or response call to other servlet resources by configuring CXFServlet or using CXF JAX-RS RequestDispatcherProvider.
Please see the JAX-RS Redirection page for more information.
XSLT and XPath
XSLT and XPath are promoted and treated as first-class citizens in CXF JAX-RS. These technologies can be very powerful when generating complex data or retrieving data of interest out of complex XML fragments.
Please see the JAX-RS Advanced XML page for more information.
Complex Search Queries
Using query parameter beans provides a way to capture search requirements that can be expressed by enumerating name/value pairs, for example, a query such as '?name=CXF&version=2.3' can be captured by a bean containing setName and setVersion methods. This 'template' bean can be used in the code to compare it against all available local data.
Versions 2.3 and later of CXF JAXRS support another option for doing advanced search queries using the Feed Item Query Language(FIQL).
Please see the JAX-RS Advanced Features page for more information.
Model-View-Controller support
XSLT
Please see this blog entry on how XSLTJaxbProvider
can be used to generate complex (X)HTML views.
JSP
With the introduction of the RequestDispatcherProvider
(see above) it is now possible for JAXRS service responses be redirected to JSP pages for further processing. Please see this beans.xml for an example.
In addition to 'resourcePath' and 'dispatcherName' properties, one can set a 'scope' property which has two possible values, 'request' and 'session' with 'request' being the default value. It affects the way the JSP code can retrieve parameters passed to it by the RequestDispatcherProvider. If it is a 'request' scope then all the parameters are set as the attributes on the current HTTP request. If session scope then they're set as the attributes on the current HTTP session.
RequestDispatcherProvider
sets the following parameters :
- JAXRS method response object. The name of this parameter is either a simple class name of this object (lower case) or a value retrieved from a beanNames map property using the fully qualified class name of this object.
- All the path, query and matrix parameters which have been initialized during the method execution
- "absolute.path", "base.path" and "relative.path" obtained from the current UriInfo
Combining JAX-WS and JAX-RS
CXF JAX-RS tries to make it easy for SOAP developers to experiment with JAX-RS and combine both JAX-WS and JAX-RS in the same service bean when needed.
Please see the JAX-RS and JAX-WS page for more information.
JAX-RS and Spring AOP
CXF JAX-RS is capable of working with AOP interceptors applied to resource classes from Spring.
For example:
<beans xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> <import resource="classpath:META-INF/cxf/cxf.xml"/> <import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml"/> <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/> <jaxrs:server id="bookservice" address="/"> <jaxrs:serviceBeans> <ref bean="bookstore"/> <ref bean="bookstoreInterface"/> </jaxrs:serviceBeans> </jaxrs:server> <bean id="bookstore" class="org.apache.cxf.systest.jaxrs.BookStore"/> <bean id="bookstoreInterface" class="org.apache.cxf.systest.jaxrs.BookStoreWithInterface"/> <aop:config> <aop:aspect id="loggingAspect" ref="simpleLogger"> <aop:before method="logBefore" pointcut="execution(* org.apache.cxf.systest.jaxrs.BookStore*.*(..))"/> <aop:after-returning method="logAfter" pointcut="execution(* org.apache.cxf.systest.jaxrs.BookStore*.*(..))"/> </aop:aspect> </aop:config> <bean id="simpleLogger" class="org.apache.cxf.systest.jaxrs.SimpleLoggingAspect"/> </beans>
Note that some AOP configuration is applied to two JAX-RS resource classes. By default Spring uses JDK dynamic proxies if a class to be proxified implements at least one interface or CGLIB proxies otherwise.
For example, here's how org.apache.cxf.systest.jaxrs.BookStoreWithInterface looks like:
public interface BookInterface { @GET @Path("/thosebooks/{bookId}/") @Produces("application/xml") Book getThatBook(Long id) throws BookNotFoundFault; } public class BookStoreWithInterface extends BookStoreStorage implements BookInterface { public Book getThatBook(@PathParam("bookId") Long id) throws BookNotFoundFault { return doGetBook(id); } @Path("/thebook") public Book getTheBook(@PathParam("bookId") Long id) throws BookNotFoundFault { return doGetBook(id); } }
In this case Spring will use a JDK dynamic proxy to wrap a BookStoreWithInterface class. As such it is important that the method which needs to be invoked such as getThatBook(...) will be part of the interface.
The other method, getTheBook() can not be dispatched to by a JAX-RS runtime as it's not possible to discover it through a JDK proxy. If this method also needs to be invoked then this method should either be added to the interface or CGLIB proxies have to be explicitly enabled (consult Spring AOP documentation for more details). For example:
<aop:config proxy-target-class="true"/>
Integration with Distributed OSGi
Distributed OSGi RI is a CXF subproject. DOSGi mandates how registered Java interfaces can be exposed
and consumed as remote services. DOSGi single and multi bundle distributions contain all the OSGI bundles required for a CXF endpoint be successfully published.
CXF JAX-RS implementations has been integrated with DOSGi RI 1.1-SNAPSHOT which makes it possible to expose Java interfaces as RESTful services and consume such services using a proxy-based client API.
Please see the DOSGI Reference page ('org.apache.cxf.rs' properties) and a greeter_rest sample for more information. Note that this demo can be run exactly as a SOAP-based greeter demo as it registers and consumes a similar (but) JAX-RS annotated GreeterService. In addition, this demo shows how one can register and consume a given interface (GreeterService2) without using explicit JAX-RS annotations but providing an out-of-band user model description.
Other Advanced Features
CXF JAX-RS provides a number of advanced extensions such as the support for the JMS transport, one-way invocations (HTTP and JMS), suspended invocations (HTTP and JMS), making existing code REST-aware by applying external user models, etc.
Please see the JAX-RS Advanced Features page for more information.
RESTful Resources
- JSR-000311 JAX-RS: The JavaTM API for RESTful Web Services
- Architectural Styles and the Design of Network-based Software Architectures
- Representational State Transfer - Wikipedia
- RESTful Web Services Cookbook - Solutions for Improving Scalability and Simplicity by Subbu Allamarajuy (O'Reilly Media, February 2010)
- RESTful Java with JAX-RS by Bill Burke (O'Reilly Media, November 2009)
- Java Web Services: Up and Running by Martin Kalin (O'Reilly Media, February 2009)
- RESTful Web Services - Web services for the real world by Leonard Richardson, Sam Ruby (O'Reilly Media, May 2007)
- RESTful Web Services by Sameer Tyagi (Oracle , August 2006)
- RESTful Web Services - "Unofficial homepage for a book about simple web services." Unknown
- How I Explained REST to My Wife by Ryan Tomayko (http://tomayko.com, December 2004)
How to contribute
CXF JAX-RS implementation sits on top of the core CXF runtime and is quite self-contained and isolated from other CXF modules such as jaxws and simple frontends.
Please check the issue list and see if you are interested in fixing one of the issues.
If you decide to go ahead then the fastest way to start is to
- do the fast trunk build using '
mvn install -Pfastinstall
' - setup the workspace 'mvn -Psetup.eclipse' which will create a workspace in a 'workspace' folder, next to 'trunk'
- import cxf modules from the trunk into the workspace and start working with the cxf-frontend-jaxrs module
If you are about to submit a patch after building a trunk/rt/frontend/jaxrs, then please also run JAX-RS system tests in trunk/systests/jaxrs :
> mvn install
You can also check out the general Getting Involved web page for more information on contributing.