Get started Bring yourself up to speed with our introductory content.

Step-by-step RESTful web service example in Java using Eclipse

TheServerSide has published a number of articles on the tenets of effective RESTful web service design, along with examples of how to actually create a cloud-native application using Spring Boot and Spring Data APIs. In this JAX-RS tutorial, we will go back to basics by developing the exact same application, except this time we'll use standard Java EE APIs. This step-by-step JAX-RS RESTful web service example in Java using Eclipse will get you up to speed on modern web service development techniques in less than 15 minutes.

Step 1: The dynamic web project

The first step in this JAX-RS tutorial is to kick off the dynamic web project creation wizard in Eclipse.

JAX-RS project creation
This JAX-RS tutorial utilizes a dynamic web project in Eclipse.

When the dynamic web project wizard appears, name the project restful-java, choose Apache Tomcat 8.5 as the target runtime, specify 3.1 as the dynamic web module version and choose a minimal configuration for the project. When these options are set, click Finish.

Note that you need to install the Apache Tomcat 8.5 server prior to doing this JAX-RS tutorial. You can still use any application server that supports the Java EE web profile, though, as the target runtime for this RESTful web service example in Java using Eclipse.

JAX-RS project settings
Specify project settings for the RESTful web service example in Java using Eclipse.

Step 2: Create the Score class

This restful web service example in Java using Eclipse models a score counter for an online rock-paper-scissors application, so the first requirement is to create a class named Score that keeps track of wins, losses and ties.

package com.mcnz.restful.java.example;
public class Score {
     public static int WINS, LOSSES, TIES;
}

To keep things simple, we won't add any setters or getters. Furthermore, we are going to make the properties of the Score class static, as that will enable the Java virtual machine (JVM) to simulate persistence between stateless calls to the web service. This approach will enable us to run and test the application on a single JVM. However, you should manage application state in this way only as a proof of concept. It's better to persist data with Hibernate and Java Persistence API or save information to a NoSQL database, but that is beyond the scope of this JAX-RS tutorial.

Step 3: Code the JAX-RS Service class

A class named ScoreService is the heart and soul of this RESTful web service example in Java using Eclipse. As such, decorate it with an ApplicationPath annotation that defines the base URL of the web service.

package com.mcnz.restful.java.example;
import javax.ws.rs.*;
 
@ApplicationPath("/")
public class ScoreService {  }

This class will contain three getter methods that enable RESTful web clients to query the number of wins, losses or ties. These methods are invoked through an HTTP GET invocation and return the current win, loss or tie count as plain text. As such, these methods each have a JAX-RS @GET annotation, a @Produces annotation indicating they return a text string and a @Path annotation indicating the URL clients need to use in order to invoke the method:

@GET @Path("/score/wins")@Produces("text/plain")
public int getWins() {return Score.WINS;}
    
@GET @Path("/score/losses")@Produces("text/plain")
public int getLosses() {return Score.LOSSES;}
    
@GET @Path("/score/ties")@Produces("text/plain")
public int getTies() {return Score.TIES;}

The increase methods of this JAX-RS tutorial's ScoreService follow a similar pattern, with the exception of the fact that each method is triggered through an HTTP POST invocation:

@POST @Path("/score/wins")@Produces("text/plain")
public int increaseWins() { return Score.WINS++; }
    
@POST @Path("/score/ties")@Produces("text/plain")     
public int increaseTies() { return Score.WINS++;}
    
@POST @Path("/score/losses")@Produces("text/plain")        
public int increaseLosses() {return Score.LOSSES++;}

The final two methods of the ScoreService class enable users to get the JSON-based representation of the complete score or pass query parameters to the web service to update the static properties of the Score class. Both methods use the /score path, and both produce JSON. But the getScore method is invoked through an HTTP GET request, while the update method is invoked through a PUT.

@GET
@Path("/score")
@Produces("application/json")
public String getScore() {
   String pattern =
      "{ \"wins\":\"%s\", \"losses\":\"%s\", \"ties\": \"%s\"}";
   return String.format(pattern,  Score.WINS, Score.LOSSES, Score.TIES );  
}
 
@PUT
@Path("/score")
@Produces("application/json")
public String update(@QueryParam("wins") int wins,
                        @QueryParam("losses") int losses,
                        @QueryParam("ties")   int ties) {
   Score.WINS   = wins;
   Score.TIES   = ties;
   Score.LOSSES = losses;
   String pattern =
      "{ \"wins\":\"%s\", \"losses\":\"%s\", \"ties\": \"%s\"}";
   return String.format(pattern,  Score.WINS, Score.LOSSES, Score.TIES );  
}

Step 4: Deploy the JAX-RS web service

Now that you've coded the JAX-RS tutorial's ScoreService, it's time for this RESTful web service example in Java using Eclipse to move into the testing stage.

To test the application, first right-click on the restful Java project, and choose Run As > Run on server. This will deploy the web project and start the Apache Tomcat server that hosts the application.

Eclipse JAX-RS deployment
Run the RESTful web services example in Java on Tomcat.

Step 5: Test the JAX-RS web service example

When you deploy the JAX-RS tutorial app, there are a number of different ways to test it. One way is to simply type the URL of the RESTful web service example into a web browser. A call to the following URL will trigger a GET invocation and a JSON string representing the initial score should be displayed:

http://localhost:8080/restful-java/score
JSON string output
Test the JAX-RS tutorial app by invoking it into a web browser.

To test the increaseTies method, run the following two curl commands in a Bash shell:

$ curl -X POST "http://localhost:8080/score/ties"
$ curl -X GET "http://localhost:8080/score/"

The JSON string returned from the second command indicates that the number of ties has indeed been incremented by one:

{ "wins":"0", "losses":"0", "ties": "1"}

Now, use curl to trigger a PUT invocation with query parameters:

$ curl -X PUT "http://localhost:8080/score?wins=1&losses=2&ties=3"

This PUT invocation will return the following JSON string:

{ "wins":"1", "losses":"2", "ties": "3"}

And that's a complete, step-by-step JAX-RS RESTful web service example in Java using Eclipse.

The full source code for this example can be downloaded from GitHub.

View All Videos

Join the conversation

1 comment

Send me notifications when other members comment.

Please create a username to comment.

How has Java EE and Eclipse helped you to develop RESTful web applications?
Cancel

-ADS BY GOOGLE

SearchCloudApplications

SearchSoftwareQuality

SearchHRSoftware

SearchSAP

SearchERP

DevOpsAgenda

Close