Skip to Content
0 %
Adding RESTful services to your app
// Explore More Tutorials

Adding RESTful services to your app


Adding RESTful services to your app

You will learn

In this tutorial you will learn how to expose RESTful services using a library called Apache CXF, which is one of the most often used implementations of the JAX-RS standard.

Step 1: Add dependency references

First, we need to add the dependency references to Apache CXF in the pom.xml file. Insert the XML snippet below just below the Servlet dependency section.

<!-- Apache CXF -->
Adding Apache CXF to the pom.xml file
Step 2: Specify CXF version property

We also need to specify the corresponding CXF version property at the end of the <properties> tag in pom.xml. See the image below for where to insert this snippet.

Adding Apache CXF to pom.xml properties element
Step 3: Create a new class

Next, create a new Class via the context menu entry New > Class of the weatherapp node in the Project Explorer. Enter the following information:

  • Package name:
  • Classname: AuthenticationService

Click on Finish.

Adding a new Java class
Step 4: Replace code

Replace the contents of with the following and save your changes.



@Produces({ MediaType.APPLICATION_JSON })
public class AuthenticationService
	@Produces({ MediaType.TEXT_PLAIN })
	public String getRemoteUser(@Context SecurityContext ctx)
		String retVal = "anonymous";
			retVal = ctx.getUserPrincipal().getName();
		catch (Exception ex)
			ex.printStackTrace(); // lazy
		return retVal;
Building out the new Java class
Step 5: Edit configuration file

Open the web.xml configuration file and copy and paste the following lines of code in between the closing </servlet-mapping> and the opening <login-config> tags:

Modifying the web.xml file for REST services
Step 6: Save and publish changes

With this, we have registered (Apache) CXF as a Servlet that listens to incoming requests using the URL-pattern: /api/v1/*. Furthermore, we registered our AuthenticationService class as one of the RESTful services. During start-up, CXF will introspect the class and use the provided JAX-RS annotations to properly configure our service.

Save your changes and publish/deploy your application.

Step 7: View the app

Navigate to the following URL: http://localhost:8080/weatherapp/api/v1/auth. After successful authentication you should see your username.

Running the Java app with RESTful API enabled

Next Steps

Back to top