Hello.
Let's continue to implement exception handling until the last time!
1: [Understanding the super basics] A brief description of MVC 2: [Prepare a template] I want to create a template with Spring Initializr and do Hello world 3: [Connection / Settings / Data display with MySQL] Save temporary data in MySQL-> Get all-> Display on top 4: [POST function] Implementation of posting function 5: [PATCH function] Switch TODO display 6: [Easy to use JpaRepository] Implementation of search function [7: [Common with Thymeleaf template fragment] Create Header] (https://qiita.com/nomad_kartman/items/8c33eca2880c43a06e40) [8: [PUT function] Implementation of editing function] (https://qiita.com/nomad_kartman/items/66578f3f91a422f9207d) [9: [Tweak] Sort TODO display in chronological order + Set due date default to today's date] (https://qiita.com/nomad_kartman/items/5ee2b13a701cf3eaeb15) 10: [Exception handling with spring] A brief summary of exception handling [11: [Exception handling in spring] Exception handling when accessing TODO with non-existent ID] (https://qiita.com/nomad_kartman/items/a486838153a563767169) [12: [Exception handling in spring] Processing when a request comes in with an unused HttpMethod / Processing when an error occurs in the server] (https://qiita.com/nomad_kartman/items/8a1a06b42138b495e29c) 13: [Exception handling with spring] TODO form validation 1: Character limit ・ Gradle update to use @Validated
Spring of this application uses Version2.3.0.RELEASE
.
If you look at 2.3 Release Notes, you can see the annotations that will be used this time, such as @Validated and @Size. It cannot be used by default.
So, according to the contents of the above link, add the validation related ones to the dependency part of build.gradle
.
build.gradle
dependencies {
//Abbreviation
implementation 'org.springframework.boot:spring-boot-starter-validation'
}
By adding this dependency, validation-related annotations can be used.
Since it is not reflected just by adding it, update gradle. Please refer to the image below.
After successfully updating, the next step is to edit the controller and check the form data class used for posting TODO.
First, let's check the validation contents of this TODO.
These are the three points. This time, I will validate the case where it is 1 to 30 characters.
java/com/example/todo/TodoForm.java
package com.example.todo;
import com.sun.istack.NotNull;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import javax.validation.constraints.Size;
import java.time.LocalDate;
@Data
public class TodoForm {
private long Id;
@NotNull
@Size(min = 1, max =30)
private String title;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate deadline;
private boolean status;
}
It looks like this.
@NotNull
does not allow null fortitle (post content)
.
@ size
can be the minimum and maximum characters.
python
@PostMapping("/register")
public String register(@Validated @ModelAttribute TodoForm formData, BindingResult error, RedirectAttributes attributes) {
if(error.hasErrors()) {
attributes.addFlashAttribute("errorMessages", error);
return "redirect:/top";
}
todoService.setTodo(formData);
return "redirect:/top";
}
Added @Validated
,BindingResult
,RedirectAttributes
.
@Validated
is an annotation that checks the validation content of the posted content TodoForm
.
Now you can check for Null and determine the number of characters.
If validation is caught, the error content is saved in the variable errorof the
BindingResult class.
RedirectAttributes
is used to return to the front.
It is a conditional branch when the error content is saved in error in the part of if (error.hasErrors ()) ...
(that is, it is stuck in validation).
We are passing error
as the variable errorMessages
to the front.
Add the following directly under the header.
resources/templates/top.html
<!--Error message display area-->
<th:block th:if="${errorMessages}">
<th:block th:each="error : ${errorMessages.getAllErrors()}">
<div class=" w-75 h-auto my-1 mx-auto pt-5">
<p class="text-center text-danger" th:text="${error.defaultMessage}"></p>
</div>
</th:block>
</th:block>
I wrote earlier that I pass errorMessages
when there is an error, but yesterday in Thymeleaf I added an if statement to determine if there is an error message.
If there are any errors, the each statement will display them all one by one.
There is th: text =" $ {error.defaultMessage} "
, but the content of the error message can be obtained with .defaultMessage
.
If you try to enter more than 30 characters, the following message will be displayed.
I won't touch it this time, but you can change this message to anything you like!
In the next article, I will touch on the remaining two validations!
Recommended Posts