Simple Application to use REST web service in Java

Technical Articles

Here we are going to build a simple web Application with the help of Jersey. If you don’t know about Jersey then it is an open source framework for developing RESTful Web Services in Java. It provides support for JAX-RS APIs and serves as a JAX-RS.

First we will create a dynamic web project in Eclipse as we have created for SOAP example. Now you will have web.xml (deployment descriptor) generated if you checked while creating dynamic project. If you have not checked for web.xml then you can generate it by Right Click on project → Java EE Tools → Generate Deployment Descriptor stub.

Now convert your project to Maven because we need to add some dependencies. So right click on project → Configure → Convert to Maven Project.

Open pom.xml to update some dependency to include the jar

Check with the pom.xml file here:-

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>SimpleRestExample</groupId>
  <artifactId>SimpleRestExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
        
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.2.3</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies> 
     <dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-bundle</artifactId>
			<version>1.19.4</version>
	 </dependency>
	 <dependency>
		    <groupId>org.json</groupId>
		    <artifactId>json</artifactId>
		    <version>20200518</version>
     </dependency>

		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-server</artifactId>
			<version>1.19.4</version>
		</dependency>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-core</artifactId>
			<version>1.19.4</version>
		</dependency>
    </dependencies>
</project>

Define the Servlet and servlet mapping in the web.xml file.

<?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>SimpleRestExample</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>/person/*</url-pattern>
	</servlet-mapping>
</web-app>

And then create the classes. I have created two classes here for getting the same data in XML and JSON format.

package com.rest.example;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;


@Path("/getPersonInXml")
public class PersonDataXml {
	@GET
	@Produces("application/xml")
	public String getPerson() {
       String name = "Saurabh";
       int age =25;
		return "<person>" + "<name>" + name + "</name>" + "<age>" + age + "</age>" + "</person>";
	}
 
	@Path("{id}")
	@GET
	@Produces("application/xml")
	public String getPersonById(@PathParam("id") int id) {
		String name = "";
		int age=0;
		if(id==1) {
			name = "Rohan";
		    age =26;
		}
		return ""+name+""+age;
		//return "<person>" + "<name>" + name + "</name>" + "<age>" + age + "</age>" + "</person>";
		
	}
}

In this class I have defined the path of the webapp and in Produces annotation it is marked as (application/xml) that means it will produce output in xml format.

package com.rest.example;

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;
import org.json.JSONException;
import org.json.JSONObject;
 
@Path("/getPersonInJson")

public class PersonDataJson {
 
	@GET
	@Produces("application/json")
	public Response getPerson() throws JSONException {
 
		JSONObject jsonObject = new JSONObject();
		String name = "Saurabh";
		int age =25;
		jsonObject.put("Name", name);
		jsonObject.put("Age", age);
 
		String result = "Person: \n\n" + jsonObject;
		return Response.status(200).entity(result).build();
	}
	
	@Path("{id}")
	@GET
	@Produces("application/json")
	public Response getPersonById(@PathParam("id") int id) throws JSONException {
        String name = "";
        int age=0;
		JSONObject jsonObject = new JSONObject();
		if(id==1) {
			name = "Rohan";
			age =26;		
		}
		jsonObject.put("Name", name);
		jsonObject.put("age", age);
 
		String result = "Person: \n\n" + jsonObject;
		return Response.status(200).entity(result).build();
	}
 
}

After that you can follow these steps to do the clean build

  • Project -> Clean
  • Project -> Right click -> Maven -> Update Project
  • Project -> Right click -> Run As.. -> Maven Clean (option 5)

Once the build is completed you will see a BUILD SUCCESS message.

After that deploy the project on Tomcat.

Now you can access the web application at the address below as per this project

For the XML data

http://localhost:8081/SimpleRestExample/person/getPersonInXml

and for the JSON data

http://localhost:8081/SimpleRestExample/person/getPersonInJson

You can also check for the address by providing id as 1

http://localhost:8081/SimpleRestExample/person/getPersonInXml/1
http://localhost:8081/SimpleRestExample/person/getPersonInJson/1

Leave a Reply

Your email address will not be published. Required fields are marked *