Spring Restful WS – Reading HTTP Post Request Body

Spread the love

Suppose the client is sending the request in the form of a JSON or XML in the request body. The server should be able to read it and process it.

The same is done with the help of the @RequestBody annotation at the server side. Let’s take a look into the below example.

Client is sending a request in the form of a JSON through Postman UI.

As seen above, it is a JSON payload which is sent in the body of the request by the Client using PostMan UI.

Now we need a mechanism at the server side to read this JSON payload. Let’s see how it is read.

First, we would need a POJO class which maps the JSON request to it. So the framework would convert the JSON sent by the client into a Java Object at the server side. The JSON properties which are name,age and designation should match with the names of the Class Fields.

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

   public void setName(String name)
   {
      this.name = name;
   }

   public void setAge(String age)
   {
      this.age = age;
   }

   public void setDesignation(String designation)
   {
      this.designation = designation;
   }

   public String getName()
   {
      return name;
   }

   public String getAge()
   {
      return age;
   }

   public String getDesignation()
   {
      return designation;
   }

}

Let’s see the actual Spring REST Controller.

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{


   @PostMapping(produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE})
   public ResponseEntity<Employee> CreateEmployee(@RequestBody EmployeeReqDetails erd)
   {

      Employee e = new Employee();
      e.setName(erd.getName());
      e.setAge(erd.getAge());
      e.setDesignation(erd.getDesignation());

      return new ResponseEntity<Employee>(e,HttpStatus.OK);
   }

}

As per the above example, the web service method reads the Post request using the @PostMapping annotation. It consumes JSON and produces JSON.

Now, using the @RequestBody annotation we read the JSON request into the POJO class EmployeeReqDetails. Using that POJO, we write the same values into an identical class Employee and return the Employee object to the client in the form of JSON. Also we return the HTTP response code as 200 for OK.

Since we are returning the response code as well apart from the JSON, we had to make use of the ResponseEntity class to achieve the same.

Hope it was clear!!!!