Spring Boot Bootcamp – Workbooks and Challenges

Workbook 8.3

In this workbook, you will validate fields from incoming request bodies.

Launch the starter project

Screen Shot 2022-07-14 at 12.59.39 AM.png

Task 1 (Review)

Inside POM.xml, add the spring-boot-starter-validation dependency. It provides the library of files needed to validate fields.

Task 2 (Review)

Apply validation constraints in the event of a blank name:

@NotBlank(message = "Name cannot be blank")

or a blank phone number:

@NotBlank(message = "Number cannot be blank")

Task 3

Recall that @Valid – based on your constraints – will validate field values that were obtained from the request body. Inside the RestController, apply the @Valid annotation where needed.

Task 4

In order to handle invalid field arguments, your global exception handler must inherit from ResponseEntityExceptionHandler

public class ApplicationExceptionHandler extends ResponseEntityExceptionHandler {

Now, override the inherited method handleMethodArgumentNotValid. Inside the method, access the result of the validation process as follows:

ex.getBindingResult().getAllErrors() //returns list of errors from validation process

Just like in section 3, the BindingResult carries the result of the validation, and getAllErrors returns a List of errors from the validation process.

For now, loop through each error inside the errors List and print its message.

for (ObjectError error : ex.getBindingResult().getAllErrors()) { System.out.println(error.getDefaultMessage()); }

Choose an appropriate status code from Mozilla Status Codes and return it.

return new ResponseEntity<>(STATUS_CODE_HERE);

Test Case: POST: localhost:8080/contact

Request Body { "name": "Tyrion Lannister", "phoneNumber": " " }

Postman Screen Shot 2022-07-14 at 1.28.17 AM.png

Terminal Output:

>> Phone number cannot be blank

Task 5

Inside ErrorResponse.java, convert your message field into a List.

private LocalDateTime timestamp; private List<String> message; <--

Fix every error inside the ErrorResponse.java.

public ErrorResponse(List<String> message) { this.message = message; this.timestamp = LocalDateTime.now(); }

Fix the errors inside handleContactNotFoundException:

ErrorResponse error = new ErrorResponse(Arrays.asList(ex.getLocalizedMessage()));

Inside handleMethodArgumentNotValid:

  • Append every error message from the BindingResult into a List<String>.
  • Create an ErrorResponse object and return it.

Test Case: POST: localhost:8080/contact

Request Body { "name": " ", "phoneNumber": " " }


Screen Shot 2022-07-14 at 1.37.12 AM.png Spring Boot serializes the message List into a JSON ARRAY type.

Good Luck!

Feedback Summary
3 students





Written Reviews
There are no written reviews yet.