
There is a way in Spring Rest to validate the incoming Http Request Body from the client. Validation is required at the server side to guarantee that the data received as input in the Request Body is valid.
There are certain annotations which we can use to implement validation at the class level.
Consider the below example showing the spring rest controller having the web method.
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}) //line 4
public ResponseEntity<Employee> CreateEmployee(@Valid @RequestBody EmployeeReqDetails erd) //line 5
{
Employee e = new Employee();
e.setName(erd.getName());
e.setAge(erd.getAge());
e.setDesignation(erd.getDesignation());
return new ResponseEntity<Employee>(e,HttpStatus.OK);
}
}
@Valid annotation is required as seen in line 5 so that validation can be configured for the request body received from the client. A json payload is received at the server side from the client.
Final set of validation is done on the POJO class EmployeeReqDetails to which the JSON request body is mapped. Kindly check the below example.
Class EmployeeReqDetails
{
@NotNull(message="Name cannot be null")
private String name;
@NotNull(message="Age cannot be null")
private String age;
@NotNull(message="Designation cannot be null")
private String designation;
....getters and setters
}
So here we have @NotNull annotation with each property which means the value received in the request body cannot be null.
If null value is recieved, the client will get an response from the server having error as bad request with response code 400.
We can configure the message at our side as well which would be sent to client incase the validation fails. message property shown above does the same.
We can add any annotations to do any kind of validations. For understanding purpose, we have used @NotNull annotation.