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

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

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 and the extended, enterprise version of Tomcat, TomEE Plus, as our deployment target. This step-by-step JAX-RS RESTful web service example in Java using Eclipse and TomEE Plus will get you up to speed on modern web service development techniques in less than 15 minutes. 

Prerequisites

This tutorial uses Eclipse Oxygen as the development environment, the underlying JDK is at version 1.8, and the deployment target is TomEE Plus. You can download TomEE Plus from the project's Apache home page.

Why are we using TomEE Plus, and not Tomcat or the standard TomEE offering? Sadly, the basic Java web profile, which Tomcat 9 implements, does not support JAX-RS, it does not include the javax.ws.rs.* packages, and without playing with POM files or adding JAR files to the Eclipse project's \lib directory, RESTful web services simply won't work. The standard TomEE offering doesn't include JAX-RS libraries either. On the other hand, the TomEE Plus server does include various enterprise packages, including JAX-RS, so RESTful web services will deploy right out of the box, making this RESTful web services example much simpler.

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 (even though we are using TomEE Plus, not Tomcat), 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 TomEE Plus prior to doing this JAX-RS tutorial. You can also use any other application server that supports Java EE and JAX-RS for this RESTful web service example in Java using Eclipse.

Where is the web.xml file?

If you look at this project in GitHub (link below), you'll notice that there isn't a web.xml file. That makes traditional enterprise developers nervous, but so long as everything is annotated, there's no need for one in version 3.x of the Servlet and JSP spec. In older REST implementations you would need to configure a Jersey Servlet and perform a REST Servlet mapping, but that is no longer necessary. In this case, TomEE Plus will process all of the annotations on the classes in the Java web project and make RESTful web sevices available accordingly. It should be noted that on some servers, you do need to reference your JAX-RS classes explicility, which you can do through an Application class. That process is addressed in the JAX-RS problems section towards the end.

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.

Just for the record, there is an easier way to return JSON from a RESTful web service than by using the String.format call. You can use @Producer annotations and simply return JavaBeans, but because we are using static variables in our Score class, doing that gets a bit messy. We will save that for a future RESTful web services tutorial with Eclipse.

@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. Remember that we are using TomEE Plus as our target server, not Tomcat. Tomcat doesn't provide built in JAX-RS support.

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 TomEE Plus 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/restful-java/score/ties"
$ curl -X GET "http://localhost:8080/restful-java/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/restful-java/score?wins=1&losses=2&ties=3"

This PUT invocation will return the following JSON string:

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

Fixing common JAX-RS problems

In this example, the ScoreService class is annotated with @ApplicationPath. This works fine with TomEE Plus, but on other servers or older implementations, the @ApplicationPath annotation is placed on a separate class that extends the JAX-RS Application class. This often solves the problem of RESTful URLs simply not being recognized and triggering a 404: The origin server did not find a current representation for the target resource error when an attempt is made to invoke them.

 import javax.ws.rs.core.Application;

@ApplicationPath("/")
public class ScoreApplication extends Application {
public Set<Class<?>> getClasses() { return new
HashSet<Class<?>>(Arrays.asList(ScoreService.class));
}
}

On servers where the implementation is Jersey based, the class can be replaced with one that is a bit easier to understand, although it calls on Jersey APIs explicitly, so it will only work with a Jersey based implementation. You just tell it the names of the various packages where JAX-RS annotated web services reside, and it ensures they are loaded:

import javax.ws.rs.ApplicationPath;

import org.glassfish.jersey.server.ResourceConfig;

@ApplicationPath("/")
public class ScoreApplication extends ResourceConfig {

public ScoreApplication() {
packages("com.mcnz.restful.java.example");
}
}

And of course, you must ensure you are using TomEE Plus and not Tomcat. As was mentioned earlier, a standard Tomcat installation will not run RESTful web services without a JAX-RS implementation added to the \lib directory, Gradle build script or Maven POM.

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

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

Create a JAX-RS web service with Tomcat, Eclipse

If you used TomEE in an attempt to create a JAX-RS web service and ran into issues, watch this new video that instead uses Tomcat and Eclipse to create this RESTful web service.

View All Videos

Join the conversation

20 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
Hi, I´m Newby and I can´t resolve my URL. I made 2 classes and I supose muy URL would be http://localhost:8080/apiRest/pruebaApi but response is 404


First Class:

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/")
public class RestApplication extends Application{

public RestApplication() {
// TODO Auto-generated constructor stub
}

}

Second Class

package api;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/pruebaApi")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class Rest {

public Rest() {
// TODO Auto-generated constructor stub
}
@GET Response helloWorld() {
return Response.ok("Primer Response para la API",MediaType.APPLICATION_JSON).build();
}

}
Cancel
I've tried changing @Path("/") instead @ApplicationPath("/")... Does not work 
Cancel

-ADS BY GOOGLE

SearchCloudApplications

SearchSoftwareQuality

SearchHRSoftware

SearchSAP

SearchERP

DevOpsAgenda

Close