Billing Software using Spring Boot Integrating Validation Framework

Suresh
3 min readOct 27, 2020

--

Spring Boot Validation Framework

Welcome back, friends!!. In this article, we will be going to see how to integrate the Spring Boot Validation framework.
I have posted this full Story in the YouTube video too. Please watch this full video.
https://youtu.be/6GhAwBqxs68

The purpose of the validation framework is, before persisting the data into DB, the System should check the data is good and quality that entered by the end-user. Spring Boot provides a very user-friendly validation framework. Using this validation framework, we can easily implement validation without writing much boilerplate code.

Let see step by step how to implement the validation framework

First Step, we need to add the following starer project in your pom.xml file. Through this artifact, we can use validation annotation in our Spring Boot request Object (In our case it is a DTO class)

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Second Step, we need to add @Valid Annotation in your Request parameter Method like below

@PostMapping("/employees")
public ResponseEntity<ResponseMessage<?>> updateEmployee(@Valid @RequestBody UserDTO requestBody)

Through this @Valid Annotation, we are enabling Spring Boot validation for UserDTO object.

Third Step, We need to add appropriate validation annotation in our Request Object. In our case, UserDTO is the request object. Since I am checking empty checks for some fields, we need to add @NotBlank Annotation in the appropriate field of UserDTO like below. Here I want to validate emailId,firstName,lastName, and mobileNo. So I have added @NotBlank Annotation for those fields.

@NotBlank(message = "Email Address can't be empty")
private String emailId;

@NotBlank(message = "First Name can't be empty")
private String firstName;

private String middleName;

@NotBlank(message = "Last Name can't be empty")
private String lastName;

@NotBlank(message = "Mobile No Name can't be empty")
private String mobileNo;

Fourth Step, We need to create a handler class that should extend from ResponseEntityExceptionHandler like below. This class should be annotated with @ControllerAdvice and @RestController

@ControllerAdvice
@RestController
public class BillingExceptionHandler extends ResponseEntityExceptionHandler {

Fifth Step, We need to override “handleMethodArgumentNotValid ” method from “ResponseEntityExceptionHandler” like below.

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException arguments, HttpHeaders headers, HttpStatus status, WebRequest request) {
BindingResult bindingResult = arguments.getBindingResult();
List<String> validationMessages = new ArrayList<>();
List<ObjectError> objectErrors = bindingResult.getAllErrors();
for (ObjectError objectError : objectErrors) {
String defaultMessage = objectError.getDefaultMessage();
validationMessages.add(defaultMessage);
}
return new ResponseEntity<>(validationMessages, HttpStatus.BAD_REQUEST);
}

Inside the override method, we need to implement our validation logic that validates against the fields which are annotated with @NotBlank. This method contains the following four parameters

MethodArgumentNotValidException arguments, HttpHeaders headers,                                                             HttpStatus status, WebRequest request

The first argument holds validation error data. The validation error data we can obtain using getBindingResult like below.

BindingResult bindingResult = arguments.getBindingResult();

The BindingResult holds whatever error made by the client. Those errors stored in the form of ObjectError in the List Object. if you want to get all errors, we need to use getAllErrors from the Binding result like below.

List<ObjectError> objectErrors = bindingResult.getAllErrors();

Let say we are keeping empty data for firstName,lastName, and mobileNo, The getAllErrors returns Three ObjectErrors those are stored in List Object.
We need iterate this List using for loop. In each iteration, we will get ObjectError. Using this class we can get the actual error message using the getDefaultMessage() method. This method returns the error message that we passed in @NotBlank Annotation. In the above code, I am collecting all errors and adding it to the validationMessages variable which is an ArrayList. Once populated all the errors in ArrayList, I am returning those errors in the form ResponseEntity like below. I am saying that the client request is a Bad Request by passing HttpStatus.BAD_REQUEST.

return new ResponseEntity<>(validationMessages, HttpStatus.BAD_REQUEST);

I hope you are enjoyed with this Story. I will come up with a good update soon. Until then bye bye Suresh.

I have posted this full Story in the YouTube video too. Please watch this full video.
https://youtu.be/6GhAwBqxs68

Take the latest code from following GitHub Repository
https://github.com/sureshstalin/billingsystem

--

--