http://opensourcesoftwareandme.blogspot.hk/2012/12/demystifying-apache-cxf-restful-hello.html
The first post of this how-to series showed you what it takes to expose a Hello World application as a SOAP over HTTP Web Service using CXF. For this post, I'll show you how to expose the same app as a RESTful service.
In the Java world, we use JAX-RS for mapping a class to a RESTful service. Giving a RESTful interface to our Hello World app is just a matter of adding JAX-RS annotations to HelloWorldImpl:
1234567891011121314151617 |
|
In the class, I tell the JAX-RS provider (i.e., CXF):
- HelloWorldImpl is a resource available on the URL relative path "/helloWorld" (@Path("/helloWorld")).
- the HTTP reply sent back to the client should have the Content-Type set to "text/hml" (@Produces).
- sayHi is to be called when the HTTP request is a GET and the relative path is "/helloWorld/sayHi/" + [variable] (@Path("sayHi/{text}")).
- to bind the URL parameter with the method argument text (@PathParam).
As in the previous how-to, I'm going to deploy the app onto an embedded Jetty server instead of deploying it onto a standalone web container:
12345678910111213141516171819202122 |
|
RuntimeDelegate.getInstance().createEndpoint(...) is a JAX-RS method that returns an unpublished endpoint. It takes in:
- a class responsible for configuring and launching the web server. This class differs across JAX-RS providers. CXF expects this class to be JAXRSServerFactoryBean.
- an object that extends Application. This user-defined class must return JAX-RS annotated classes responsible for processing client requests. For us, this means returning HelloWorldImpl:
1234567891011121314151617 |
|
Before testing the service, I add the required CXF libraries to the Java classpath by declaring them as dependencies in project's POM :
1234567891011121314 |
|
If you compare this POM with the POM of the first how-to, you'll note that now I've swapped the JAX-WS frontend with the JAX-RS one.
All that is left is to run the server with the following Maven commands:
1 |
|
Once the server is up, accessing via your browser the URL http://localhost:9000/helloWorld/sayHi/Ricston should give you "Hello Ricston".