Restful Web Service Tutorial with Apache CXF
Nowadays, it is more common to work with RESTful Web Service than with SOAP based Web service. This is also a very popular job interview question and I have discussed the reasons at Web Services Interview Questions and Answers. Apache CXF is a popular framework for developing both style Web services. This tutorial extends the "simple Web" Java EE tutorial.
Step 1: You need to bring in the relevant CXF framework JAR files. The transitive dependencies will bring in the other dependent Spring jar files, JAXB jar files, and many other jar files listed in the screenshot below.
Modify the pom.xml file as shown below:
Now, if you right-mouse-click on simpleWeb, and select "Maven --> Update Depencies", you can see all the transitively dependent jar files in the "Java Perspective" as shown below.
As you can see, it transitively brings in Spring and JAXB jars in addition to other relevant jars.
Step 2: Define the RESTful Web Service interface and implementation classes with relevant annotations
Step 3: Define the "User" bean (or POJO -- Plain Old Java Object) class with the relevant annotations to marshall (i.e. convert object to XML) User object to relevant XML. Generally, these objects can be generated from a XSD file and running it through "xjc" compiler supplied with JAXB. This is demonstrated at "RESTful Web Service Overview".
This will marshal the user object to XML like
Step 4: Define the web service endpoint via cxf.xml, which internally uses the Spring framework. Define this undersr/main/resources folder under a package com.mytutorial.webservice.
Step 5: Define the web.xml with the CXFServlet and tell where to find the cxf.xml file.
You should now have the relevant artifacts as shown below.
Step 6: Deploy the simpleWeb.war to the Tomcat server from within eclipse or from outside eclipse as described in the simple web JEE tutorial.
Step 7: Open a wen browser like google chrome, and type the following URL -> http://localhost:8080/simpleWeb/. This will list the RESTful services that are available.
Step 8: Finally, invoke the web service via the URL --> http://localhost:8080/simpleWeb/userservices/userservice/1.0/user/John to get an output as shown below. The username supplied is "John". If you are accessing it via a Java application, you can use a framework likeApache HttpClient to make an HTTP call.