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

18 comments

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
Can you show web.xml file?
I am getting error that 
HTTP Status 500 - Class com.service.HelloWorldService is not a Servlet
Cancel
What is a web.xml file?

This application actually doesn't have one. They are not required for modern web applications.

Take a look at the source code here:

https://github.com/cameronmcnz/java-jakarta-ee/tree/master/restful-java
Cancel
this example does not work
Cancel
The video shows the development, uninterrupted, from start to finish. So you can watch and see each step in the process. The source code is available here if you want to double-check your code:
https://github.com/cameronmcnz/java-jakarta-ee/tree/master/restful-java
Cancel
I have used the same code as yours, but when i try use the HTTP GET request, i receive a HTTP 404 Error with message as "The origin server did not find a current representation for the target resource or is not willing to disclose that one exists"
Cancel
having the same problem here and noting that i'm new to java and the tomcat configuration.. is there any chance that my tomcat (v8.5.37) is not configured to resolve restfull services?
Cancel
nice tutorial thanks.
Cancel
https://github.com/cameronmcnz/java-jakarta-ee/tree/master/restful-java
Cancel
 "The origin server did not find a current representation for the target resource or is not willing to disclose that one exists"
Cancel
Hi, I have the same issue as this.  The server is running but not doing the routing.

After moving some src code around, I now have an error in Eclipse that JAX (javax.ws) cannot be resolved.  It seems that jar needs to be loaded - in addition to JDK 1.8. 

Cancel
Thanks for the very helpful hello-world restful-web-services tutorial, which I ran on a Mac OS.  Like others, I ran into all sorts of problems following the written instructions and copy-pasting the code; however, watching the video and eyeballing the source code helped resolve my issues.  It's actually good that the written instructions weren't totally accurate - this forced me to pay attention to what I was doing.  Some observations:
1: I believe you meant "TomEE Plus" not "TomEE" (which apparently doesn't include the JAX WS RS.
2: Some minor errors in the source code (no biggie)
3: Command line is slighty different in bash on Mac OS (need to escape the ampersand, no need to enclose the url in double quotes
4: error in some of the URL specifications (missing restful-java app context in path)
Or am I missing something?

Cancel
  • The code on Github has a bug at 
	@POST @Path("/score/ties")@Produces("text/plain")
	public int increaseTies() {return Score.WINS++;}
WINS must be replaced with TIES.
  • I experienced the same problem that other readers have that is: 

HTTP 404 Error with a message "The origin server did not find a current representation for the target resource or is not willing to disclose that one exists" 

After some search and trials, I solved the problem by adding the @Path annotation to the service class as follows: 

		@ApplicationPath("/")
		@Path("")
		public class ScoreService  {
I thought this could help.

Cancel
Then I am getting error :
"The annotation @ApplicationPath is disallowed for this location"
Cancel
Hi, 

I have applied your complete code but getting error.


Type Status Report

Message /restful-java/score

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.




Cancel
"The origin server did not find a current representation for the target resource or is not willing to disclose that one exists". This is issue because Tomcat does not have support for Rest Services API you need to install TomEE plus
Cancel
Were you able to run it on TomEE Plus ? I still can't , I'm still getting 'The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.'  .... Can someone help me. 

HTTP Status 404 – Not Found


Type Status Report

Message /restful-java/score/

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.


Apache Tomcat (TomEE)/9.0.12 (8.0.0-M1)

Cancel
hi ,

change the @ApplicationPath("/")
public class ScoreService {  } with @Path("/")
Cancel

-ADS BY GOOGLE

SearchCloudApplications

SearchSoftwareQuality

SearchHRSoftware

SearchSAP

SearchERP

DevOpsAgenda

Close