Spring Restful WS – Store Employees Temporary

Spread the love

We will take a look into the below example in which we will store of list of employees in a map using a POST request and retrieve the same employees stored using a GET method.

We will use a Map in the below example for storing of employees data.

First we will create a new employee using a POST method and store the same in a Map.

Class EmployeeReqDetails
{
   private String name;
   private String age;
   private String designation;

.... public getters and setters
}

Class Employee
{
   private String empId;
   private String name;
   private String age;
   private String designation;

....public getters and setters

}


com.techfinanceworld.restapp.controller;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("employees")
public Class EmpController{

Map<String, Employee> emps;

   @PostMapping(produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE}) //line 4
   public ResponseEntity<Employee> CreateEmployee(@RequestBody EmployeeReqDetails erd) //line 5
   {
      Employee e = new Employee();
      e.setName(erd.getName());
      e.setAge(erd.getAge());
      e.setDesignation(erd.getDesignation());

      String empId = Math.random().toString();
      e.setEmpId(empId);

      if (emps = null){
        emps = new HashMap<>();
      }

      emps.put(empId,emp);
      return new ResponseEntity<Employee>(e,HttpStatus.OK);
   }

}

As seen above, we are using an map named emps.

Post request is sent by the client in JSON format with the employee details for creation. Same is fetched from the RequestBody into the erd bean of EmployeeReqDetails class as seen in line 5.

Then we populate the Employee emp bean properties with the erd bean and set the emp id. The emp bean is inserted into the map and the same emp bean is send as a JSON resp back to client.

Now we will retrieve the same employee details which were inserted into the map using GET method.

@GetMapping(path="/{empId}",produces = {MediaType.APPLICATION_JSON_VALUE})
public String getEmployee(@PathVariable String empId)
{
     if(emps.containsKey(empId)){
        return new ResponseEntity<Employee>(emps.get(empId),HttpStatus.OK);
     }
     else{
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
     }

}

As seen above, the map is checked for the empId which is sent from the client’s GET request.

If it exists in map, the employee details are sent as response in JSON format or else a response code is returned signifying NO CONTENT.