JAX-RS Restful WebService using CXF

JAX-RS Restful WebService using CXF

learninjava
Aug 06, 2015 - Webservices
 

WebService 

Any service which follows the REST (REpresentational State Transfer) architectural pattern is said to be restful. Let us look at an example on how to create a simple restful webservice using CXF and Spring. The following software has been used for this tutorial :
1. Apache Maven 3.0.4
2. Spring 3.2.6
3. Apache CXF 3.0.3
4. Jetty 6.1.10/Tomcat 7
First, we need to create a basic CXF web project structure. For this, use the below command :
mvn archetype:generate -DgroupId=com.learninjava -DartifactId=cxfjaxrsws
-DarchetypeArtifactId=org.apache.cxf.archetype:cxf-jaxrs-service -DinteractiveMode=false
 Remember!
1. If the archetype is not found due to future maven changes, you can simply use the below command :
mvn archetype:generate
Now, select the appropriate archetype serial number from the list provided. On our development environment, the serial number for our tutorial is,
514: remote -> org.apache.cxf.archetype:cxf-jaxrs-service (Simple CXF JAX-RS webapp service using Spring configuration)
2. You can actually create a restful webservice without even writing a single line of code.
See here : restful-webservice-using-cxf-and-maven
Remember, you will just get an unpolished version of the project with out concepts being explained. So, we recommend going through the below tutorial.
If the command is successful, your basic project structure should look similar to the below :
restful-webservice-project-structure
 Remember!
You CANNOT use the Test case files provided by this archetype without modification because if you do so, you cannot run the unit test file (client). This is because the maven surefire plugin expects the test file names in the following patterns :
**/Test*.java
**/*Test.java
**/*TestCase.java
but the archetype creates the Test case file as HelloWorldIT.java
Maven does not consider this file (HelloWorldIT.java) as a test case as there is no 'Test' string in the file name. For this purpose, we have renamed the test file to HelloAngryWorldTest.java to make sure the junit tests are run properly and also there were many changes made to pom.xml. For instance, we have removed some unused configurations and refactored the configurations for easy and better understanding.
For your convenience, we have provided configurations for running the webservice on both Jetty and Tomcat servers.
First, let us take a look at tomcat configuration. Later we will see about jetty configuration. There is a cool feature in jetty that attracts many developers. we will see what is it later in this tutorial.
 

Using Tomcat : 

1. Change the default pom.xml as below :

loading...
You will notice that there are 4 important plugins in the pom.xml out of which 2 are optional. We will see each of them in detail :
maven-surefire-plugin - [Optional] This plugin is added to specify the service.url in the pom.xml itself. We will see its usage while running the web service client.
tomcat7-maven-plugin - This is the tomcat plugin where will deploy our angry world webservice.
maven-compiler-plugin - This plugin specifies the Java compiler source and target versions.
maven-eclipse-plugin - [Optional] This plugin is used to generate the .classpath and .project files which enables us to use this project in eclipse.
The other important sections includes dependencies and properties which are used to specify the jar file dependencies and properties respectively.

2. Renamed HelloWorld.java to HelloAngryWorld.java :

loading...
This is the actual webservice source file, so lets take a look at it.
This webservice exposes two methods one of type plain text and other of type JsonBean. These methods uses some important annotations:
@Path - annotation at class level specifies the context path to access this webservice.
@Path - annotation at method level specifies the path to access the actual method in the webservice.
@PathParam - annotation is used to accept input from the request URL path specified by @Path.
@Produces - annotation is used to specify the return type of the method.
@Consumes - annotation is used to specify the return type accepted as input to a method.
For a complete listing of annotations refer : jax-rs-annotations

3. JsonBean.java :

loading...

4. beans.xml :

loading...
PreferencesPlaceholderConfigurer and ServletContextPropertyPlaceholderConfigurer are used to handle properties files. See references section at the bottom of this tutorial for more information.The beans.xml has 2 important tags under <jaxrs:server> tag which is the most important tag in this xml.
<jaxrs:serviceBeans> - This lists all the service beans which are nothing but the services we want to make as a webservice
<jaxrs:providers> - This is to specify the provider which are used to extend the JAX-RS runtime. There are 3 types of providers: Entity providers, Context providers and Exception providers. Here Jackson is an alternative provider is used. Refer to the JAX-RS specification link provided in references section for more info. Please note that this is an optional configuration as there is already a default Json provider included with JAX-RS called Jettison (org.apache.cxf.jaxrs.provider.json.JSONProvider).
Observe that names of the entities like service, server etc. These are in conjunction with REST architecture. You will find these names to be different when dealing with JAX-WS

5. web.xml :

loading...
The configurations in web.xml are straighforward. CXFServlet is the actual servlet that reads the xml configurations and makes the service beans as webservices and handles the requests and responses to the exposed services.
ContextLoaderListener is the ROOT web application context that is used by spring.
Once the above files are ready, type the below command to start the tomcat container :
mvn clean package -DskipTests=true tomcat7:run
This command cleans the target directory, compiles, builds war and deploys it to tomcat. Notice that we used skipTests = true switch. This is to make sure that the test case are not run before the server starts.
Navigate to the URL :
http://localhost:9090/jaxrs-service/helloAngryWorld/echo/tweet
Output:

tweet

This is an echo service so whatever you input in the URL should be echoed to your browser.
If you are unware of your endpoint address, you can use the below url to find out,
http://localhost:9090/jaxrs-service/cxf/services
This lists all the REST and SOAP services running on your server.
 

Using Jetty : 

1. pom.xml :

The pom.xml is pretty much similar to the one we have used for tomcat configuration except that the tomcat plugin is replaced with the jetty equivalent. Also the port number is changed 8080 just to distinguish between tomcat and jetty.
loading...
All other steps are same as above.
To start the jetty container and the webservice use the below command :
mvn clean package -DskipTests=true jetty:run
Navigate to the URL :
http://localhost:8080/jaxrs-service/helloAngryWorld/echo/tweet
Output:

tweet

 

Advantage of using Jetty - Hot code deployment : 

By default, Jetty scans the following directories :
target/classes - for changes to Java sources and
src/main/webapp - for changes to web sources.
If any source file is modified, the changes are autodeployed to the jetty container without manually restarting for the changes to take effect.
To test this hot code deployment, try to change any source file. We have changed the Path param of ping method from echo to ping. Now, recompiled the source using mvn compile command.
The moment the source file is compiled, notice the server console. You will observe that jetty hot deploys the code automatically and you can access the changes via browser instantly.
Navigate to the URL :
http://localhost:8080/jaxrs-service/helloAngryWorld/ping/tweet
Output:

tweet

Thats all folks !! Happy coding. If you feel this helped you, keep supporting us by   or  or  below or on the articles on social media.
 
Like us on: