RESTful Web Service

This example shows how to implement a RESTful web service that converts tablespoons to cups. This example service handles text/html. Its client application has a JavaFX user interface that prompts the user for the number of tablespoons and passes the user value to the server where the server converts the number of tablespoons to cups. The server passes the conversion information back to the client, which displays it to the user.

The example was built with the following software configuration:

  • JDK1.8.0_45
  • Apache Tomcat v8.0.36
  • Eclipse Mars.2 Release (4.6.0)

Steps

  1. Create a Dynamic Web Project
  2. Configure as a Maven Project
  3. Add Maven Dependencies
  4. Update web.xml file with project information
  5. Create Package and  Java Classes
  6. Clean, Update, and Build Project
  7. Deploy Project to Server
  8. Start Tomcat Sever
  9. Test Your Web Service
  10. Exercise

1.  Create a Dynamic Web Project

  1. Start Eclipse.
  2. Select File > New > Project to display the New Project wizard.
  3. In the New Project wizard, navigate to Web > Dynamic Web Project.
  4. Click Next to display the New Dynamic Web Project window.
  5. In the New Dynamic Web Project window, in the Project Name field, type UIBakerRESTJerseyServer.
  6. Click Finish.

2. Configure as a Maven Project

  1. Right-click the UIBakerRESTJerseyService project.
  2. In the drop-down menu, select Configure > Maven Project.
    A pom.xml file displays at the end of your project.

3. Add MAVEN Dependencies

  1. Right-click the pom.xml file.
  2. In the drop-down menu, select Open With > Maven POM Editor.
  3. In the Maven POM editor,select the Dependencies tab at the bottom.
  4. In the Dependencies tab, click the Add button to add the following dependencies.

Tips: Use the Enter groupId, artifactId, etc. field to find them. For example, type asm in the field and expand each result until you find 3.3.1.

  • asm :  3.3.1
  • jersey-bundle: 1.19
  • jersey-server : 1.19
  • jersey-core : 1.19
  • json : 20140107: To find this one, type org.json in the field and scroll to org.json json in the list. Expand it to find 20140107.

Note: If you get the  Index downloads are disabled, search results may be incomplete message when you add dependencies, do this:

  1. Select Window > Preferences.
  2. In the left side, select Maven.
  3. Check the Download repository index updates on startup box.

Your final pom.xml file should look like this:

<project xmlns="http://maven.apache.org/POM/4.0.0" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>UIBakerRESTJerseyServer</groupId>
  <artifactId>UIBakerRESTJerseyServer</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.6</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
      <dependency>
          <groupId>asm</groupId>
          <artifactId>asm-all</artifactId>
          <version>3.3.1</version>
      </dependency>
      <dependency>
          <groupId>com.sun.jersey</groupId>
          <artifactId>jersey-server</artifactId>
          <version>1.19.1</version>
      </dependency>
      <dependency>
          <groupId>com.sun.jersey</groupId>
          <artifactId>jersey-core</artifactId>
          <version>1.19.1</version>
      </dependency>
      <dependency>
          <groupId>org.json</groupId>
          <artifactId>json</artifactId>
          <version>20140107</version>
      </dependency>
      <dependency>
          <groupId>com.sun.jersey</groupId>
          <artifactId>jersey-bundle</artifactId>
          <version>1.19</version>
      </dependency>
  </dependencies>
</project>

4. Update web.xml file

Add the information below flagged in bold to your web.xml file, or copy and paste the entire web.xml content below into your project web.xml file. The com.sun.jersey.spi.container.servlet.ServletContainer class is part of the JAX-RS API run time. It works with the generated classes to get the application resources.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns="http://java.sun.com/xml/ns/javaee" 
  xmlns:web="http://java.sun.com/xml/ns/javaee" 
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
  http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
  version="3.0">
  <display-name>UIBakerRESTJerseyServer</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey Web Application</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

5. Create Package and Java Classes

  1. In your UIBakerRESTJerseyServer project under Java Resources > src, add the com.rest.jersey package.
  2. Under the com.rest.jersey package, add the TbsCupsService class.
  3. Copy the following code into the class appropriate files.

Note: When you copy and paste code from this blog, the quotes do not copy correctly. To fix the errors in Eclipse, replace the copied quotes with the quotes that Eclipse uses.

About the service class: REST is URL based, and uses annotations to form the URL (@PATH), to indicate which information to retrieve (@GET), and its format (@Produces). In this example, the format is text/html (@Produces(“text/html”).

The class has two convert methods that perform the math to go from tablespoons to cups. One method has no parameters and supplies a default value for tablespoons,  and one that accepts one parameter that indicates the number of tablespoons. The @PathParam annotation indicates a method parameter value passed to the service through the URL.

TbsCupsService class:

package com.rest.jersey;
 
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
 
@Path("/ttocservice")
public class TbsCupsService { 
  @GET
  @Produces("text/html")
  public Response convertTbstoCups() throws Exception {
    Double tbs = 32.0;
    Double cups;
    cups = (tbs/16.0);
    
    Double calc[];
    calc = new Double[2];
    calc[0] = tbs;
    calc[1] = cups;
      
    String result = "@Produces(\"text/html\") Output: \n\nTbs to Cups Output: \n\n" + "Tablespoons = " + calc[0] + "\n" + "Cups = " + calc[1];
    return Response.status(200).entity(result).build();
  }
  @Path("{t}")
  @GET
  @Produces("text/html")
  public Response convertTbstoCupsfromInput(@PathParam("t") 
    Double t) throws Exception { 
    Double cups;
    Double tbs = t;
    cups =  (tbs/16.0);
    
    Double calc[];
    calc = new Double[2];
    calc[0] = tbs;
    calc[1] = cups;
      
    String result = "@Produces(\"text/html\") Output: \n\nTbs to Cups Output: \n\n" + "Tablespoons = " + calc[0] + "\n" + "Cups = " + calc[1];
    return Response.status(200).entity(result).build();
  }
}

Note: If Eclipse flags errors next to the package imports, it means the project isn’t finding the Maven dependencies. To fix this, go to the next step and follow the instructions to Clean and Update the project.

6. Clean, Update, and Build

Clean:

  1. Select the UIBakerRESTJerseyServer project.
  2. Select Project > Clean

Update:

  1. Select the UIBakerRESTJerseyServer project.
  2. Select Maven > Update Project.

Build:

  1. Select the UIBakerRESTJerseyServer project.
  2. Select Run As > 5. Maven Build.
  3. In the Edit Configuration dialog box in the Goals field, type clean install.
  4. Click Apply and then click Run.
  5. Check the Console window for a successful build.
    You should see something like this:
...
[INFO] ----------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ----------------------------------------------------
[INFO] Total time: 2.437 s
[INFO] Finished at: 2016-06-23T14:52:13-07:00
[INFO] Final Memory: 18M/176M
[INFO] -----------------------------------------------------

7. Deploy Project to Server

  1. In the Servers tab, right-click Tomcat Server <version> at localhost.
  2. Select Add and Remove . . .
  3. In the Add and Remove dialog, select the UIBakerRESTJerseyServer project from left side and click Add and Finish.

8. Start Tomcat Server

  1. Right click Tomcat Server <version> at localhost.
  2. Select Start.

If you get the The ResourceConfig instance does not contain any root resource classes server error, do the following:

  1. On your Windows computer, go to  ~\workspace\UIBakerRESTJerseyServer\target\classes
  2. Copy the package and class (com.rest.jersey.*) to
    ~\workspace\BakerRESTJerseyServer\WebContent\WEB-INF\classes
  3. Do Clean, Update, Build, and Deploy

9. Test Your Web Service

You test the web service from a browser with a URI in the following format, which invoke the methods in each service that do not have parameters.

<protocol>://<service-name>/<ResourceType>/<ResourceID>
http://localhost:8080/UIBakerRESTJerseyServer/rest/ttocservice

ttocservice No Parameter Output:

@Produces("text/html") 
Output: Tbs to Cups Output: 
Tablespoons = 32.0 Cups = 2.0

To invoke the parameterized methods, add a numeric value at the end to indicate the number of tablespoons (ttocservice) to convert to cups as follows:

<protocol>://<service-name>/<ResourceType>/<ResourceID>/<Value>
http://localhost:8080/UIBakerRESTJerseyServer/rest/ttocservice/16

ttocservice Parameterized Output:

@Produces("text/html") 
Output: Tbs to Cups Output: 
Tablespoons = 16.0 Cups = 1.0

Note: Because a web service is accessed by many clients, once you make a URI public, it should always be available. If you must update a URI, use a redirect with the status code 300 to send clients from the old URI to the new one.

10. Exercise

Use the TbsCupsService class as a model for creating a class that converts cups to tablespoons.

 

Advertisements
RESTful Web Service

One thought on “RESTful Web Service

  1. […] Add the needed dependencies until the dependencies are the same as the following. Note that you can just copy and paste the repositories stanza (shown in bold) into the file into the location shown below. However, add the other dependencies through the pom editor as described in RESTful Web Service. […]

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s