Overview
In software development, it is important to do some validation for security purposes and also lessen the unexpected errors, but it takes a lot of hours just to implement specific validation methods. In this post, I will share the easiest way on how to validate your request body in Spring Boot.
Let's get started
Add dependency
Add the spring boot starter validation to your project. You can do this by adding the code below to your pom.xml
.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Update your controller
Let's say you have a login API that authenticates the user. All you need to do is add the @Valid
annotation to your request body. For this example I added the @Valid
annotation to my userLoginRequestModel
. This signals Spring Boot to do some validation of the model.
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
IUserService userService;
@PostMapping("/login")
public UserLoginResponseModel login(@Valid @RequestBody UserLoginRequestModel userLoginRequestModel) {
return userService.login(userLoginRequestModel);
}
}
Update your model
In your model, all you need to add is the specific validation annotation that we want to implement. For this example, I used the @NotEmpty
annotation to make sure the username and password is required. I also added the message parameter.
public class UserLoginRequestModel {
@NotEmpty(message = "Username is required.")
private String username;
@NotEmpty(message = "Password is required.")
private String password;
//...
}
There are a lot of validations you can use, such as @Min
and @Max
, make sure to check the documentation.
Update your exception handler
To display the validation results, It is better to handle the error in your exception handler method.
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleValidationExceptions(
MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach((error) -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
return errors;
}
Test
Now, try to test the validation in your API. The result should return something like this.
{
"Username is required.",
"Password is required."
}
Conclusion
Spring Boot makes it way easier to do validation just by using the @Valid
annotation. No need to implement validation methods that sometimes may not work. So make sure to try this out.
Top comments (0)