Spring RESTFUL WS – Sending Response Code To Client

Spread the love

Suppose the server wants to send a response code back to the client, in that case Spring REST provides an ResponseEntity Class.

Let us take a look at the below example.

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

   @GetMapping(path="/{empId}")
   public ResponseEntity<Employee> getEmployee(@PathVariable String empId) //Line 4
   {
        Employee emp = new Employee();
        emp.setName("John");
        emp.setAge("50");
        emp.setDesignation("Software Engineer");

        return new ResponseEntity<Employee>(HttpStatus.BAD_REQUEST);   
   }
}

As per the above example we are returning an ResponseEntity having the response code which is defined by the Property HttpStatus.BAD_REQUEST.

The value of the property HttpStatus.BAD_REQUEST = 400 and it is returned as the response code.

As seen above, we are returning only the response code and not the body. We can return the response code as well as the body if we use a different constructor for the ResponseEntity.

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

   @GetMapping(path="/{empId}")
   public ResponseEntity<Employee> getEmployee(@PathVariable String empId) //Line 4
   {
        Employee emp = new Employee();
        emp.setName("John");
        emp.setAge("50");
        emp.setDesignation("Software Engineer");

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

In the above example, we sending the response body which is the emp object sent as default response type json and the response code for HttpStatus.OK which is 200.