Implementing WebService (RESTFul) in JAVA using Jersey JARs

 

In this tutorial I will show you how to implement Restful web service in java using jersey jars. But before that let us discuss little bit about web service.

What is a web service?

Web Services are nothing but the client side applications which provide a standardise way of integrating web based application using open standards over Internet protocol. Simply saying, it’s a collection of standards or protocols for exchanging information between two applications or devices. Web Services are categorised into two categories. One is SOAP based and another is RESTful. Because of several reasons, now-a-days RESTful web services are used. So, I’ll show how to implement RESTful web services in JAVA here.

Required Resources:
Jersey jars and google Gson jars. A web server is required to host the web service, here I am using Tomcat 7.

Folder Structure:
Folder Structure of Web Services in Java

Files:
1)web.xml :
This is the deployment descriptor of the application. We need to configure “org.glassfish.jersey.servlet.ServletContainer” in this file and have to set as 1 to instantiate this servlet at the time of deployment. The package off the class which we want to expose as web service has to be configured as init to the above servlet having as “jersey.config.server.provider.packages”.

<?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>WebServiceExample</display-name>
  <servlet>
  	<servlet-name>jersyServlet</servlet-name>
  	<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
  	<init-param>  
        <param-name>jersey.config.server.provider.packages</param-name>  
        <param-value>com.restproject.service</param-value>  
    </init-param>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  	<servlet-name>jersyServlet</servlet-name>
  	<url-pattern>/services/*</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

2)Employee.java:
This is a simple VO whose json string we are sending from client to the service and upon receiving we are converting the json string to Employee object.

package com.restproject.vo;

import java.io.Serializable;

public class Employee implements Serializable{

	private static final long serialVersionUID = 1L;
	private String name;
	private String address;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}	
}

3)SampleService.java:
This the service class which we are exposing as a web service. We have set the class level annotation @Path to “/myService”. So whenever a request comes with this URL will be handled by this service. In method level we have used annotations to specify the HTTP method and type of data allowed as method parameter(here we have used json).

package com.restproject.service;

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

import com.google.gson.Gson;
import com.restproject.vo.Employee;

@Path("/myService")
public class SampleService {
	
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public Response printMessage(String employeeJson){
		System.out.println("employeeJson : "+employeeJson);
		Gson gson = new Gson();
		Employee employee = gson.fromJson(employeeJson, Employee.class);
		System.out.println("employee : "+employee);
		System.out.println(employee.getName());
		return Response.ok("SUCCESS").build();
	}
}

4)SampleClient.java:
This is the java class from where we are invoking the web service.

package com.restproject.client;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.client.ClientConfig;

public class SampleClient {
	public static void main(String[] args) {
		Client client = ClientBuilder.newClient(new ClientConfig());
		WebTarget webTarget = client.target("http://localhost:8080/WebServiceExample/services").path("myService");
		String jsonString = "{'name':'test','age':'26','address':'india'}";
		webTarget.queryParam("employee", jsonString);
		Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
		Response response = invocationBuilder.accept(MediaType.APPLICATION_JSON).post(Entity.json(jsonString));
		if(response.getStatus() != 200){
			throw new RuntimeException("HTTP Error code : "+response.getStatus());
		}
		System.out.println("Response Text from web serviec : "+response.readEntity(String.class));
	}
}

Leave a comment

SUBSCRIBE TO NEWSLETTER

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Categories