Java Libraries
Use JAR files which are listed below:
antlr-2.7.7.jar
aopalliance-1.0.jar
asm-debug-all-3.2.jar
aspectjrt-1.8.5.jar
cglib-2.2.jar
commons-logging-1.2.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-core-4.3.10.Final.jar
hibernate-entitymanager-4.3.10.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
jackson-annotations-2.4.1.jar
jackson-core-2.4.1.jar
jackson-databind-2.4.1.1.jar
jandex-1.1.0.Final.jar
javassist-3.18.1-GA.jar
javax.persistence-2.0.0.jar
javax.servlet-api-3.1.0.jar
javax.servlet.jsp.jstl-1.2.2.jar
javax.servlet.jsp.jstl-api-1.2.1.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
jcl-over-slf4j-1.7.10.jar
jstl-1.2.jar
mysql-connector-java-5.1.36.jar
slf4j-api-1.7.10.jar
spring-aop-4.1.5.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
spring-beans-4.1.5.RELEASE.jar
spring-context-4.1.5.RELEASE.jar
spring-core-4.1.5.RELEASE.jar
spring-data-commons-1.10.0.RELEASE.jar
spring-data-jpa-1.8.0.RELEASE.jar
spring-expression-4.3.3.RELEASE.jar
spring-framework-bom-4.0.0.RELEASE.jar
spring-jdbc-4.0.9.RELEASE.jar
spring-orm-4.0.9.RELEASE.jar
spring-tx-4.0.9.RELEASE.jar
spring-web-4.0.6.RELEASE.jar
spring-webmvc-4.0.6.RELEASE.jar
taglibs-standard-impl-1.2.1.jar
xml-apis-1.0.b2.jar
Create Database
Create a database with the name is learnspringrestfulwebservices. This database have a table: Products table
--
-- Table structure for table `products`
--
CREATE TABLE `product` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(250) NOT NULL,
`price` decimal(10,1) NOT NULL,
`quantity` int(11) NOT NULL,
`status` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `products`
--
INSERT INTO `products` (`name`, `price`, `quantity`, `status`) VALUES('name 1', '12.2', 2, 1);
INSERT INTO `products` (`name`, `price`, `quantity`, `status`) VALUES('name 2', '6.5', 6, 1);
INSERT INTO `products` (`name`, `price`, `quantity`, `status`) VALUES('name 3', '11.8', 8, 1);
Create Server Project
Create Dynamic Web Project in Eclipse and add the below configuration to 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">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Spring Restful Web Services Configuration File
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="demo.*" />
<mvc:annotation-driven />
<jpa:repositories base-package="demo.repositories" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/learnspringrestfulwebservices" />
<property name="username" value="root" />
<property name="password" value="123456" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="demo.entities" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
</bean>
</beans>
Entity Class
Create entities package in server project. Create a entity class: Product.java as below
Product.java
package demo.entities;
import java.math.BigDecimal;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "product")
public class Product{
private int id;
private String name;
private BigDecimal price;
private int quantity;
private boolean status;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
}
Project Structure
Create ProductRepository Interface
The ProductRepository interface extends from CrudRepository interface of Spring Data JPA that provides CRUD operations for an entity.
package demo.repositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import demo.entities.Product;
@Repository("productRepository")
public interface ProductRepository extends CrudRepository<Product, Integer> {
}
Create ProductService Interface
The ProductService interface contains methods to interact with the database.
package demo.services;
import demo.entities.Product;
public interface ProductService {
public Product create(Product product);
}
Create ProductServiceImpl class
The ProductServiceImpl class implements methods from ProductService interfaces that contains methods to interact with the database.
package demo.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import demo.entities.Product;
import demo.repositories.ProductRepository;
@Service("productService")
@Transactional
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductRepository productRepository;
@Override
public Product create(Product product) {
return productRepository.save(product);
}
}
Create Rest API Controller
Create Rest API Controller provides application/json data for the client
package demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import demo.entities.Product;
import demo.services.ProductService;
@RestController
@RequestMapping("product")
public class ProductRestController {
@Autowired
private ProductService productService;
@RequestMapping(
value = "create",
method = RequestMethod.POST,
produces = { MimeTypeUtils.APPLICATION_JSON_VALUE },
consumes = { MimeTypeUtils.APPLICATION_JSON_VALUE },
headers = "Accept=application/json"
)
public ResponseEntity<Product> create(@RequestBody Product product) {
try {
return new ResponseEntity<Product>(productService.create(product), HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<Product>(HttpStatus.BAD_REQUEST);
}
}
}
Consume Rest API Controller from Console Application
Create Java Project in Eclipse
Entity Class
Create entities package in Console Application. Create a entity class: Product.java as below
Product.java
package entities;
import java.math.BigDecimal;
public class Product {
private int id;
private String name;
private BigDecimal price;
private int quantity;
private boolean status;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
}
Create DemoRestClientModel
DemoRestClientModel class contain methods call Web API
package models;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import entities.Product;
public class DemoRestClientModel {
private String BASE_URL = "http://localhost:8086/LearnSpringRestfulWebServices_Server/api/product/";
private RestTemplate restTemplate = new RestTemplate();
public ResponseEntity<Product> create(Product product) {
try {
return restTemplate.postForEntity(BASE_URL + "create", product, Product.class);
} catch (Exception e) {
return null;
}
}
}
Run Application
package main;
import java.math.BigDecimal;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import entities.Product;
import models.DemoRestClientModel;
public class Main {
public static void main(String[] args) {
DemoRestClientModel demoRestClientModel = new DemoRestClientModel();
Product product = new Product();
product.setName("name 4");
product.setPrice(BigDecimal.valueOf(123));
product.setQuantity(5);
product.setStatus(true);
ResponseEntity<Product> responseEntity = demoRestClientModel.create(product);
if (responseEntity != null) {
HttpStatus httpStatus = responseEntity.getStatusCode();
System.out.println("Status Code: " + httpStatus);
Product productInfo = responseEntity.getBody();
System.out.println("Inserted Id: " + productInfo.getId());
} else {
System.out.println("Can not connect to find web method");
}
}
}
Output
Status Code: 200
Inserted Id: 5