Sunday, April 23, 2017

Java Program for JSON RESTful Web Service Example

In this post, I intend to provide the sample code to prepare a Java RESTful web service to GET and POST JSON message. Jersey has been used to create the service.

Here is the Dynamic Web Project structure:
(Ignore the errors. Update Maven and those will be gone. The below code works fine.)




  • web.xml:


<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Restful Web Application</display-name>
  <servlet>
    <servlet-name>jersey-XMLExample-serlvet</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</param-value>
    </init-param>
    <init-param>
      <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
      <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>jersey-XMLExample-serlvet</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>


  • pom.xml:


<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>com.javacodegeeks.enterprise.rest.jersey</groupId>
<artifactId>JerseyJSONExample</artifactId>
<version>0.0.1-SNAPSHOT</version>

<repositories>
<repository>
<id>maven2-repository.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
<layout>default</layout>
</repository>
</repositories>

<dependencies>

<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.9</version>
</dependency>

<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.9</version>
</dependency>

<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.9</version>
</dependency>



</dependencies>

</project>


  • Student.java:


package com.webService;


public class Student {

private int id;
private String firstName;
private String lastName;
private int age;

// Must have no-argument constructor
public Student() {

}

public Student(String fname, String lname, int age, int id) {
this.firstName = fname;
this.lastName = lname;
this.age = age;
this.id = id;
}

public void setFirstName(String fname) {
this.firstName = fname;
}

public String getFirstName() {
return this.firstName;
}


public void setLastName(String lname) {
this.lastName = lname;
}

public String getLastName() {
return this.lastName;
}


public void setAge(int age) {
this.age = age;
}

public int getAge() {
return this.age;
}


public void setId(int id) {
this.id = id;
}

public int getId() {
return this.id;
}

@Override
public String toString() {
return new StringBuffer(" First Name : ").append(this.firstName)
.append(" Last Name : ").append(this.lastName)
.append(" Age : ").append(this.age).append(" ID : ")
.append(this.id).toString();
}

}


  • JerseyRestService.java:


package com.webService;

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

@Path("/jsonServices")
public class JerseyRestService {


@GET
@Path("/show/{name}")
@Produces(MediaType.APPLICATION_JSON)
public Student produceJSON( @PathParam("name") String name ) {

Student st = new Student(name,"Mathews",36,1);

return st;

}

@POST
@Path("/sendMessage")
@Consumes(MediaType.APPLICATION_JSON)
public Response consumeJSON( Student student ) {

String output = student.toString();

return Response.status(200).entity(output).build();
}

}

  • JerseyClient.java:

package com.serviceClient;
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;
import com.sun.jersey.api.json.JSONConfiguration;
import com.webService.Student;
// http://localhost:8080/JavaWebService/rest/jsonServices/show/Pradeep -- GET
// http://localhost:8080/JavaWebService/rest/jsonServices/sendMessage -- POST
/*{
 "id": 1,
 "firstName": "MS",
 "lastName": "Dhoni",
 "age": 35
}*/
public class JerseyClient {

public static void main(String[] args) {
try {

Student st = new Student("Steve", "Smith", 28, 8);
ClientConfig clientConfig = new DefaultClientConfig();

clientConfig.getFeatures().put(
JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

Client client = Client.create(clientConfig);

WebResource webResource = client
.resource("http://localhost:8080/JavaWebService/rest/jsonServices/sendMessage");

ClientResponse response = webResource.accept("application/json")
.type("application/json").post(ClientResponse.class, st);

if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}

String output = response.getEntity(String.class);

System.out.println("Server response! \n");
System.out.println(output);

} catch (Exception e) {

e.printStackTrace();

}

}

}


Run the Project on Server (e.g: Tomcat/Wildfly) and user the below URLs to see how it works:

  • GET:

http://localhost:8080/JavaWebService/rest/jsonServices/show/George


  • POST:

http://localhost:8080/JavaWebService/rest/jsonServices/sendMessage

Use the below JSON message to post from Postman or any other tool you prefer.

{
 "id": 1,
 "firstName": "MS",
 "lastName": "Dhoni",
 "age": 35
}