Creating restful web services with JSON response using Spring

Building  restful web service in Java  using spring with JSON response

In our previous posts  Spring MVC applications we have created lots Spring based Java web application.In this post we are going to learn restful web services using Spring with JSON response.We are going to use Jackson library to get the response in JSON format.

We are going to create a web application which will act as service for client applications.
Spring Restful web services folder structure
  • Update the pom.xml file.
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.javainstance</groupId>
<artifactId>SpringRest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>


<properties>
<springframework.version>4.3.1.RELEASE</springframework.version>
<jackson.version>2.7.5</jackson.version>
</properties>

<dependencies>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>


<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>

</dependencies>
<build>
<finalName>SpringRest</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>

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

</project> 


  • Create folder structure as shown.


Model


Product.java

package com.javainstance.model;

/**
 * @author javainstance
 *
 */
public class Product {

private int productId;

private String productName;

private String productDescription;

public Product(int productId, String productName, String productDescription) {
super();
this.productId = productId;
this.productName = productName;
this.productDescription = productDescription;
}

public int getProductId() {
return productId;
}

public void setProductId(int productId) {
this.productId = productId;
}

public String getProductName() {
return productName;
}

public void setProductName(String productName) {
this.productName = productName;
}

public String getProductDescription() {
return productDescription;
}

public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}


}


Data Access Object (DAO Layer)

This layer interact with the database.In this example we are using dummy data from arraylist.

DaoImpl.java

package com.javainstance.dao;

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

import org.springframework.stereotype.Component;

import com.javainstance.model.Product;


/**
 * @author javainstance
 *
 */
@Component
public class DaoImpl {

static ArrayList<Product> products = null;
static {

products = new ArrayList<>();
Product product1 = new Product(1, "Iphone", "Iphone 6S");
Product product2 = new Product(2, "Refrigerator", "Samsung advance cool");
Product product3 = new Product(3, "Television", "LG Led");
products.add(product1);
products.add(product2);
products.add(product3);

}

public Product getProduct(int productId) {

for (Product product : products) {
if (product.getProductId()==productId) {
return product;
}
}
return null;
}

public List<Product> getAllProducts() {

return products;
}

public void addProduct(Product product) {
products.add(product);
}
}



Rest Controller

We are using annotation based configuration for rest controller.@RestController to declare class as rest controller.
@GetMapping- For handling get request to fetch the data.
@PostMapping- For post the form data to server.

We have other options also such 
@PutMapping- To update the data.
@DeleteMapping- To delete the data

ProductController.java

package com.javainstance.controller;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.javainstance.dao.DaoImpl;
import com.javainstance.model.Product;

/**
 * @author javainstance
 *
 */
@RestController
public class ProductController {

@Autowired
private DaoImpl dao;

@GetMapping(value = "/getAllProducts")
public List<Product> getAllProduct() {
List<Product> prodList = new ArrayList<>();

prodList = dao.getAllProducts();
return prodList;
}

@GetMapping("/getProduct/{productId}")
public Product getArticleDetail(@PathVariable Integer productId) {
Product prod = null;

prod = dao.getProduct(productId);
return prod;
}

@PostMapping(value = "/addProduct")
public Product addProduct(@RequestBody Product product) {
dao.addProduct(product);
return product;

}

}

Configuration Files

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" version="3.0">
  <display-name>SpringRest</display-name>
  <servlet>
    <servlet-name>main</servlet-name>
    <servlet-class>
                org.springframework.web.servlet.DispatcherServlet
            </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>main</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

main-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<context:component-scan base-package="com.javainstance"/>
<mvc:annotation-driven/>




</beans>  

Start the tomcat server and test the service

To get all products:

URL- http://localhost:8080/SpringRest/rest/getAllProducts

Output:
[{"productId":1,"productName":"Iphone","productDescription":"Iphone 6S"},{"productId":2,"productName":"Refrigerator","productDescription":"Samsung advance cool"},{"productId":3,"productName":"Television","productDescription":"LG Led"}]


To get product by Id:

URL- http://localhost:8080/SpringRest/rest/getProduct/1

Output:

{"productId":1,"productName":"Iphone","productDescription":"Iphone 6S"}

Note : To Test the post method we need form data to posted to server which requires client to 
get consumed.
Application of Spring restful web services Spring MVC rest controller with AngularJS

Spring Restful Web Services - Download CodeCode from Github 

CRUD Application Spring MVC-Hibernate-MySql-Maven

Give you suggestion in comments.If you like the post Share with your friends on social network.


     











Creating restful web services with JSON response using Spring Creating restful web services with JSON response using Spring Reviewed by JavaInstance on 9:54:00 AM Rating: 5

No comments:

Powered by Blogger.