RESTful web services JAXRS json example using jersey

This post is in continuation with web service tutorial (Part -8).
    Introduction to web services Web services interview questions SOAP web service introduction RESTful web service introduction Difference between SOAP and REST web services SOAP web service example in java using eclipse JAX-WS web service eclipse tutorial JAX-WS web service deployment on tomcat Create RESTful web service in java(JAX-RS) using jersey RESTful web service JAXRS json example using jersey RESTful web service JAXRS CRUD example using jersey AngularJS RESTful web service JAXRS CRUD example using $http RESTful Web Services (JAX-RS) @QueryParam Example Spring Rest simple example Spring Rest json example Spring Rest xml example Spring Rest CRUD example
In previous post, we have created a very simple Restful web services(JAXRS) using jersey which returns xml. In this post, we will see Restful web services(JAXRS) using jersey which will return json as response.

Here are steps to create a simple Restful web services(JAXRS)  using jersey which will return json.

1) Create a dynamic web project using maven in eclipse named "JAXRSJsonExample"
2) We need to add jersey jars utility in the classpath. 
 
 <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-servlet</artifactId>
   <version>${jersey.version}</version>
 </dependency>
 <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-json</artifactId>
   <version>${jersey.version}</version>
 </dependency>
 

Jersey internally uses Jackson for Json Handling, so it will be used to marshal pojo objects to JSON.
Now create pom.xml as follows:
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/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.arpit.java2blog</groupId>
 <artifactId>JAXRSJsonExample</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>JAXRSJsonExample Maven Webapp</name>
 <url>http://maven.apache.org</url>
   <properties>
        <jersey.version>1.18.3</jersey.version>
    </properties>
 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>
  
  <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-servlet</artifactId>
   <version>${jersey.version}</version>
  </dependency>
  <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-json</artifactId>
   <version>${jersey.version}</version>
  </dependency>

  <dependency>
   <groupId>commons-logging</groupId>
   <artifactId>commons-logging</artifactId>
   <version>1.2</version>
  </dependency>
 </dependencies>
 <build>
  <finalName>JAXRSJsonExample</finalName>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.3</version>
    <configuration>
     <source>1.7</source>
     <target>1.7</target>
    </configuration>
   </plugin>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <configuration>
     <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>


   </plugin>
  </plugins>
 </build>

</project>

Application configuration:

3) create web.xml as below:
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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>Archetype Created Web Application</display-name>
  <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>       
        <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-serlvet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

Create bean class 

4) Create a bean name "Country.java" in org.arpit.java2blog.bean.
package org.arpit.java2blog.bean;

public class Country{
 
 int id;
 String countryName; 
 
 public Country(int i, String countryName) {
  super();
  this.id = i;
  this.countryName = countryName;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getCountryName() {
  return countryName;
 }
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 } 
 
}

Create CountryRestService 

5) Create a controller named "CountryRestService.java"
package org.arpit.java2blog.jaxrs;

import java.util.ArrayList;
import java.util.List;

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;

import org.arpit.java2blog.bean.Country;
/* 
 * author: Arpit Mandliya
 * */
@Path("/countries")
public class CountryRestService {
 
    @GET
    @Produces(MediaType.APPLICATION_JSON)
 public List<Country> getCountries()
 {
  List<Country> listOfCountries = new ArrayList<Country>();
  listOfCountries=createCountryList();
  return listOfCountries;
 }

 @GET
    @Path("{id: \\d+}")
    @Produces(MediaType.APPLICATION_JSON)
 public Country getCountryById(@PathParam("id") int id)
 {
  List<Country> listOfCountries = new ArrayList<Country>();
  listOfCountries=createCountryList();

  for (Country country: listOfCountries) {
   if(country.getId()==id)
    return country;
  }
  
  return null;
 }

// Utiliy method to create country list.
 public List<Country> createCountryList()
 {
  Country indiaCountry=new Country(1, "India");
  Country chinaCountry=new Country(4, "China");
  Country nepalCountry=new Country(3, "Nepal");
  Country bhutanCountry=new Country(2, "Bhutan");

  List<Country> listOfCountries = new ArrayList<Country>();
  listOfCountries.add(indiaCountry);
  listOfCountries.add(chinaCountry);
  listOfCountries.add(nepalCountry);
  listOfCountries.add(bhutanCountry);
  return listOfCountries;
 }
}
@Path(/your_path_at_class_level) : Sets the path to base URL + /your_path_at_class_level. The base URL is based on your application name, the servlet and the URL pattern from the web.xml" configuration file.

@Path(/your_path_at_method_level): Sets path to base URL + /your_path_at_class_level+ /your_path_at_method_level

@Produces(MediaType.APPLICATION_JSON[, more-types ]): @Produces defines which MIME type is delivered by a method annotated with @GET. In the example text ("text/json") is produced.

6) It 's time to do maven build.
Right click on project -> Run as -> Maven build

7) Provide goals as clean install (given below) and click on run


Run the application

8) Right click on project -> run as -> run on server
Select apache tomcat and click on finish

9) Test your REST service under: "http://localhost:8080/JAXRSJsonExample/rest/countries".
You will get following output:


10) Now pass country id as parameter to url.
"http://localhost:8080/JAXRSJsonExample/rest/countries/3".

click to begin
20KB .zip

Project structure:


We are done with Restful web services json example using jersey. If you are still facing any issue, please comment.

If you getting 404 error with above steps, you may need to follow below steps:


1) If you are getting this warning into your Tomcat startup console log, then it can cause the issue

WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server: JAXRSJsonExample' did not find a matching property.

This particular warning basically means that the <Context> element in Tomcat's server.xml contains an unknown attribute source and that Tomcat doesn't know what to do with this attribute and therefore will ignore it.
To resolve this in eclipse,
Remove the project from the server from the Server View. Right click on server -> add and remove

then remove project from server configuration.
Then run the project under the same server. Warning should be removed now
Or if warning still remains then
  • Go to server view
  • Double click on your tomcat server. It will open the server configuration.
  • Under server options check ‘Publish module contents to separate XML files’ checkbox. 
  • Restart your server. This time your page will come without any issues.
2) Try to update Maven project.
Right click on project ->Maven-> update project
then

This should solve you issues.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012