Restful Web Service with Java

March 28, 2016by Dan

REST stands for Representational State Transfer, was first introduced by Roy Fielding in his thesis “Architectural Styles and the Design of Network-based Software Architectures” in year 2000. REST is an architectural style. HTTP is a protocol which contains the set of REST architectural constraints.

REST principals

  • Everything in REST is considered as a resource.
  • Every resource has an URI
  • Uses uniform interfaces. Resources are handled using POST, GET, PUT, DELETE operations which are similar to CRUD operations.
  • Be stateless.
  • Communications are done via representations, like XML, JSON

RESTful Web Services

RESTful Web Services have embraced by large service providers across the web as an alternative to SOAP based Web Services due to its simplicity. This post will demonstrate how to create a RESTful Web Service and client using Jersey framework which extends JAX-RS API.

Why we need this?

Actually everyone need this when it comes to sync communication between modules, domains or two totally different applications. Of course there are other methods of doing this (sync or async), but REST, from our point of view, is the easiest and fastest solution in this case. We use rest to communicate between runnable applications that are doing domain specific business logic. This helps to have one single entry point in your code which is accessed by multiple clients. We have declared resource URLs that are used by clients like WEB, third party libs, standalone apps etc.

Creating RESTful Web Service

  • Create a new dynamic web project called “RESTfulWS”
  • Download Jersey zip bundle from here. Add libs as dependency to your project
  • In your project, inside Java Resources -> src create a new package called “com.dannnnn.tech.restws”. Inside it create a new java class called “ProductInfo”. Also include the given web.xml file inside WEB-INF folder.

ProductInfo.java

[code language=”java”]
package com.dannnnn.tech.restws;

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

/**
*
* @author dcebotarenco
*/
// @Path here defines class level path. Identifies the URI path that
// a resource class will serve requests for.
@Path("ProductInfoService")
public class ProductInfo {
// @GET here defines, this method will method will process HTTP GET
// requests.

@GET
// @Path here defines method level path. Identifies the URI path that a
// resource class method will serve requests for.
@Path("/name/{i}")
// @Produces here defines the media type(s) that the methods
// of a resource class can produce.
@Produces(MediaType.TEXT_XML)
// @PathParam injects the value of URI parameter that defined in @Path
// expression, into the method.
public String productName(@PathParam("i") String i) {

String name = i;
return "" + "" + name + "" + "";
}
@GET
@Path("/serialnumber/{j}")
@Produces(MediaType.TEXT_XML)
public String productSerialNumber(@PathParam("j") int j) {
int serialnumber = j;
return "" + "" + serialnumber + "" + "";
}
}
[/code]

web.xml

[code language=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xmlns:web="https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>RESTfulWS</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.dannnnn.tech.restws</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
[/code]

  • To run the project, right click on it and click on run as ->run on server.
  • Execute the following URL in your browser and you’ll see the output.

[code]
https://localhost:8080/RESTfulWS/rest/ProductInfoService/name/xBox
[/code]

Output

[code language=”xml”]
<Product>
<Name>xBox</Name>
</Product>
[/code]

Creating Client

Create a package called “com.dannnnn.tech.restclient”. Inside it create a java class called “ProductInfoClient”.

ProductInfoClient.java

[code language=”java”]
package com.dannnnn.tech.restclient;

import javax.ws.rs.core.MediaType;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

/**
*
* @author dcebotarenco
*
*/
public class ProductInfoClient {

public static final String BASE_URI = "https://localhost:8080/RESTfulWS";
public static final String PATH_NAME = "/ProductInfoService/name/";
public static final String PATH_SN = "/ProductInfoService/serialnumber/";

public static void main(String[] args) {

String product = "xBox";
int serialnumber = 2300001;

ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource resource = client.resource(BASE_URI);

WebResource nameResource = resource.path("rest").path(PATH_NAME + name);
System.out.println("Client Response n"
+ getClientResponse(nameResource));
System.out.println("Response n" + getResponse(nameResource) + "nn");

WebResource snResource = resource.path("rest").path(PATH_SN + serialnumber);
System.out.println("Client Response n"
+ getClientResponse(snResource));
System.out.println("Response n" + getResponse(snResource));
}

/**
* Returns client response. e.g : GET https://localhost:8080/RESTfulWS/rest/ProductInfoService/name/xBox returned a response status of 200 OK
*
* @param service
* @return
*/
private static String getClientResponse(WebResource resource) {
return resource.accept(MediaType.TEXT_XML).get(ClientResponse.class)
.toString();
}

/**
* Returns the response as XML e.g : <Product><Name>xBox</Name></ Product >
*
* @param service
* @return
*/
private static String getResponse(WebResource resource) {
return resource.accept(MediaType.TEXT_XML).get(String.class);
}
}
[/code]

Once you run the client program, you’ll get following output.

[code]
Client Response
GET https://localhost:8080/RESTfulWS/rest/ProductInfoService/name/xBox returned a response status of 200 OK
Response
xBox

Client Response
GET https://localhost:8080/RESTfulWS/rest/ProductInfoService/serialnumber/2300001 returned a response status of 200 OK
Response
2300001
[/code]

Enjoy!

Upscale Your

Business TODAY
Connect with us
Bulgara Street 33/1, Chisinau MD-2001, Moldova
+ 373 22 996 170
info@isd-soft.com
De Amfoor 15, 5807 GW Venray-Oostrum, The Netherlands
+31 6 212 94 116

Subscribe to our newsletter today to receive updates on the latest news, releases and special offers.

Copyright ©2024, ISD. All rights reserved | Cookies Policy | Privacy Policy

De Nederlandse pagina’s zijn vertaald met behulp van een AI-applicatie.