Skip to Content

End-to-End Weather App Scenario Part 5

By akula86

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.


  1. 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
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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.

  7. 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

Updated 12/08/2016

Time to Complete

10 min



Back to top