Java Spring Rest webservice CRUD example

Connect with

Spring rest web service example with CRUD operationsStep by step Java Spring rest web service example with CRUD: Create, Read, Update, Delete operations using JDK 8, Eclipse IDE , maven build tool, Tomcat web server.

1. PreRequisite for Spring Rest web service example

For Spring Rest application , I have tested in following environment:
– JDK 8
– Eclipse IDE
– Maven 3.3
– Tomcat 7
– Advance Rest Client

If you want to know the basic dependency of Maven for this project, you can go through another post to download this project from GitHub.

2. Controller class for Spring rest web service example

This is controller class for this demo project.

package com.mysoftkey.springrest.controller;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.mysoftkey.springrest.model.Customer;
import com.mysoftkey.springrest.service.CustomerService;

/**
 * This is controller class for Restful webservice in Spring to 
 * handle all Cutomer related method.
 * 
 * @author ranjeet jha
 *
 */
//@RestController
@Controller
@RequestMapping(value="/customer")
public class CustomerController {

 private final Logger logger = LoggerFactory.getLogger(CustomerController.class);

 @Autowired
 private CustomerService customerService;
 
 @RequestMapping(value = "/hello", method = RequestMethod.GET)
 public ResponseEntity getHello() {
  return new ResponseEntity("Hello", HttpStatus.OK);
 }
 
 /**
  * This method is used to get list of Customer object.
  * url: http://localhost:8080/springRestCRUD/customer/
  * 
  * @return
  */
 @RequestMapping(value = "/", method = RequestMethod.GET)
 public ResponseEntity 	 	 	 	 	 	 	 	> getCustomerListHandler() {
  List customerList = null;
  HttpStatus status = HttpStatus.OK;
  try {
   customerList = customerService.getCustomers();
   if (customerList == null) {
    
   }
  } catch (Exception e) {
   status = HttpStatus.BAD_REQUEST;
  }

  return new ResponseEntity 	 	 	 	 	 	 	 	>(customerList, status);
 }

 /**
  * This method is used to get one Customer object by id.
  * 
  * @param id
  * @return
  */
 @RequestMapping(value = "/{id}", method = RequestMethod.GET)
 public ResponseEntity getCustomer(@PathVariable("id") Long id) {
  System.out.println("called at : " +new Date());
  Customer customer = null;
  MultiValueMap resHeader = new LinkedMultiValueMap();
  try {
   customer = customerService.getCustomerById(id);
   
   Calendar cal = Calendar.getInstance();
   cal.add(Calendar.MINUTE, 1);
   resHeader.add("Expires", cal.getTime().toString());
   resHeader.add("Date", new Date().toString());
   if (customer == null) {
    customer = new Customer();
   // return new ResponseEntity("No Customer found for ID " + id, HttpStatus.NOT_FOUND);
   }
  } catch (Exception e) {
  }
  //return new ResponseEntity(customer, HttpStatus.OK);
  return new ResponseEntity(customer, resHeader, HttpStatus.OK);
 }

 /**
  * This method is used to add Customer object.
  * 
  * @param customer
  * @return
  */
 @RequestMapping(value = "/add", method = RequestMethod.POST)
 public ResponseEntity> addCustomerHandler(@RequestBody Customer customer) {
 
  Map response = new HashMap();
  HttpStatus status = HttpStatus.OK;
  try {
   customerService.addCustomer(customer);
   response.put("customer", customer);
   response.put("ok", 1);
   response.put("messge", "successfully added customer object");
  } catch (Exception e) {
   logger.error("Exception caught while adding customer , msg: ", e.getMessage());
   response.put("ok", 0);
   response.put("messge", "something went wrong");
   response.put("error", e.getMessage());
   status = HttpStatus.BAD_REQUEST;
  }

  return new ResponseEntity>(response, status);
 }

 /**
  * This method is used to delete Customer object by id.
  * 
  * @param id
  * @return
  */
 @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
 public ResponseEntity> deleteCustomerHandler(@PathVariable("id") Long id) {
  boolean status = false;
  HttpStatus httpStatus = HttpStatus.OK;
  Map response = new HashMap();
  try {
   status = customerService.deleteCustomerById(id);
   if (!status) {
    return new ResponseEntity("No Customer found to delete for ID " + id, HttpStatus.NOT_FOUND);
   }
   response.put("ok", 1);
   response.put("messge", "successfully deleted");
   logger.debug("succefully deleted , id: ", id);
  } catch (Exception e) {
   response.put("ok", 0);
   response.put("messge", "something went wrong");
   response.put("error", e.getMessage());
   httpStatus = HttpStatus.BAD_REQUEST;
  }
  return new ResponseEntity>(response, httpStatus);
 }

 /**
  * This method is used to update Customer object for provided payload json.
  * 
  * @param id
  * @param customer
  * @return
  */
 @RequestMapping(value = "{id}", method = RequestMethod.PUT)
 public ResponseEntity> updateCustomer(@PathVariable Long id, @RequestBody Customer customer) {
  boolean isUpdated = false;
  HttpStatus status = HttpStatus.OK;
  Map response = new HashMap();
  try {
   isUpdated = customerService.upateCustomer(customer);
   
   if (!isUpdated) {
    response.put("ok", 1);
    response.put("messge", "successfully deleted");
    logger.debug("succefully deleted , id: ", id);
   } else {
    response.put("ok", 1);
    response.put("messge", "No customer found for id: "+ id);
    logger.debug("No customer found for id: ", id);
   }
  } catch (Exception e) {
   response.put("ok", 0);
   response.put("messge", "Exception occured while update, msg:" + e.getMessage());
   logger.debug("No customer found for id: ", id);
  }

  return new ResponseEntity>(response, status);
 }

}

3. Service Interface

We should encourage interface before implementation of Implementation. So I created interface first then its implementation class.

package com.mysoftkey.springrest.dao;

import java.util.List;

import com.mysoftkey.springrest.model.Customer;

/**
 * This is DAO (Data Access Object) to interact with repository.
 * 
 * @author Ranjeet Jha
 *
 */
public interface CustomerDao {

 /**
  * This method is used to add Customer object in repository.
  * 
  * @param customer
  * @throws Exception
  */
 public boolean addCustomer(Customer customer) throws Exception;
 
 /**
  * This method is used to update Customer object in repository.
  * 
  * @param customer
  * @throws Exception
  */
 public boolean upateCustomer(Customer customer) throws Exception;
 
 /**
  * This method is used to delete Customer object by provided id from repository.
  * 
  * @param id
  * @throws Exception
  */
 public boolean deleteCustomerById(Long id) throws Exception;
 
 /**
  * This method is used to get list of all Customer object from repository.
  * 
  * @return
  * @throws Exception
  */
 public List getCustomers() throws Exception;
 
 /**
  * This method is used to get Customer object by customer id from repository.
  * 
  * @param id
  * @return
  * @throws Exception
  */
 public Customer getCustomerById(Long id) throws Exception;
 
}

4. Service Impl class

This is service implementation class for Customer entity.

package com.mysoftkey.springrest.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mysoftkey.springrest.dao.CustomerDao;
import com.mysoftkey.springrest.model.Customer;

/**
 * This service impl class is used for customer entity.
 * 
 * @author Ranjeet Jha
 *
 */
@Service("customerService")
public class CustomerServiceImpl implements CustomerService{

 @Autowired
 private CustomerDao customerDao;
 
 public void addCustomer(Customer customer) throws Exception {
  customerDao.addCustomer(customer);
  
 }

 public boolean upateCustomer(Customer customer) throws Exception {
  return customerDao.upateCustomer(customer);
  
 }

 public boolean deleteCustomerById(Long id) throws Exception {
  return customerDao.deleteCustomerById(id);
  
 }

 public List getCustomers() throws Exception {
  return customerDao.getCustomers();
 }

 public Customer getCustomerById(Long id) throws Exception {
  return customerDao.getCustomerById(id);
 }

}

5. DAO (Data Access Object) Interface

package com.mysoftkey.springrest.dao;

import java.util.List;

import com.mysoftkey.springrest.model.Customer;

/**
 * This is DAO (Data Access Object) to interact with repository.
 * 
 * @author Ranjeet Jha
 *
 */
public interface CustomerDao {

 /**
  * This method is used to add Customer object in repository.
  * 
  * @param customer
  * @throws Exception
  */
 public boolean addCustomer(Customer customer) throws Exception;
 
 /**
  * This method is used to update Customer object in repository.
  * 
  * @param customer
  * @throws Exception
  */
 public boolean upateCustomer(Customer customer) throws Exception;
 
 /**
  * This method is used to delete Customer object by provided id from repository.
  * 
  * @param id
  * @throws Exception
  */
 public boolean deleteCustomerById(Long id) throws Exception;
 
 /**
  * This method is used to get list of all Customer object from repository.
  * 
  * @return
  * @throws Exception
  */
 public List getCustomers() throws Exception;
 
 /**
  * This method is used to get Customer object by customer id from repository.
  * 
  * @param id
  * @return
  * @throws Exception
  */
 public Customer getCustomerById(Long id) throws Exception;
 
}

6. DAO (Data Access Object) Implementation

/**
 * 
 */
package com.mysoftkey.springrest.dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.mysoftkey.springrest.model.Customer;

/**
 * this implementation class is DAO (Data Access Object) for Customer entity.
 * 
 * @author ranjeet jha
 *
 */
@Repository("customerDao")
public class CustomerDaoImpl implements CustomerDao {

 private final Logger logger = LoggerFactory.getLogger(CustomerDaoImpl.class);

 // this is in-memory customer repository for demonstration purpose
 private static List customers = new ArrayList();
 
 // get the incremented value and initialize with 1 (provided arg)
 AtomicLong atomicLong = new AtomicLong(1);

 
 public void init() {
  customers.add(new Customer(atomicLong.getAndIncrement(), "ranjeet", 35));
  customers.add(new Customer(atomicLong.getAndIncrement(), "Mukesh", 35));
 }
 
 public boolean addCustomer(Customer customer) throws Exception {
  customer.setId(atomicLong.getAndIncrement());
  return customers.add(customer);

 }

 public boolean upateCustomer(Customer customer) throws Exception {
  for (Customer c : customers) {
   if (c.getId().equals(customer.getId())) {
    customer.setId(c.getId());
    customers.remove(c);
    customers.add(customer);
    logger.debug("updated customer by customer id : ", customer.getId());
    return true;
   }
  }
  return false;
 }

 public boolean deleteCustomerById(Long id) throws Exception {
  boolean status = false;
  Iterator it = customers.iterator();
   while(it.hasNext()) {
    Customer c = it.next();
    if (c.getId() == id) {
     it.remove();
     logger.debug("removed customer by customer id : ", id);
     status = true;
    }
   }
   return status;
 }

 public List getCustomers() throws Exception {
  return customers;
 }

 public Customer getCustomerById(Long id) throws Exception {
  for (Customer c : customers) {
   if (c.getId() == id) {
    return c;
   }

  }
  return null;

 }
}

6. Different Client to call all methods

Following is the step by step mandatory things which you should know before calling either via Google’s Advanced Rest Client. or any programming code base.

To Add Customer

Service URL

http://localhost:8080/springRestCRUD/customer/add

Request header:
In Request header provide this or from Rest client provide this.

Content-Type: application/json

PayLoad JSON:

{"name":"ranjeet", "age":44}

Outout:

{
"messge": "successfully added customer object",
"ok": 1,
"customer": {
  "id": 1,
  "name": "ranjeet",
  "age": 44
 }
}

To Get Customer

Service URL
provided 1 as id of customer in the pathVariable, which is part of the url.

http://localhost:8080/springRestCRUD/customer/1

Http Method: POST

Request header:
In Request header provide this or from Rest client provide this.

Content-Type: application/json

PayLoad JSON: Not Applicable , as we are getting based on id

Outout:

{
"id": 1,
"name": "ranjeet",
"age": 44
}

To update Customer for rest web services example

Service URL

http://localhost:8080/springRestCRUD/customer/1

Http Method: PUT

Request header:
In Request header provide this or from Rest client provide this.

Content-Type: application/json

PayLoad JSON:

{"id":1, "name":"ranjeet Jha", "age":44}

Outout:

{
"messge": "No customer found for id: 1",
"ok": 1
}

To Delete Customer

Service URL

http://localhost:8080/springRestCRUD/customer/1

Http Method: DELETE

Request header:
In Request header provide this or from Rest client provide this.

Content-Type: application/json

PayLoad JSON:

{"name":"ranjeet", "age":44}

Outout:

{
"messge": "successfully deleted",
"ok": 1
}

To Get All Customers

Service URL

http://localhost:8080/springRestCRUD/customer/

Http Method: DELETE

Request header:

Content-Type: application/json

PayLoad JSON: Not applicable as method is get.

Outout:

[
  {
    "id": 2,
    "name": "ranjeet",
    "age": 45
  },
  {
    "id": 3,
    "name": "ranjeet",
    "age": 45
  }
]

8. Download Source code of spring web service rest example

You can download this source code here for Java Spring Web service rest example.
Download spring Rest CRUD Example


Connect with

Leave a Comment

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