Let's create a TODO application in Java 13 TODO form validation 1: Character limit ・ Gradle update to use @Validated

Hello.

Let's continue to implement exception handling until the last time!

TODO application creation link collection

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

Add a new dependency to Gradle

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.

Added to build.grale

build.gradle


dependencies {
	//Abbreviation
	implementation 'org.springframework.boot:spring-boot-starter-validation'
	}

By adding this dependency, validation-related annotations can be used.

update build.gradle

Since it is not reflected just by adding it, update gradle. Please refer to the image below. Screen Shot 0002-11-07 at 20.16.03.png

After successfully updating, the next step is to edit the controller and check the form data class used for posting TODO.

Perform validation

Confirmation of posted content

First, let's check the validation contents of this TODO.

  1. The posted content is 1 to 30 characters
  2. Empty string is not allowed
  3. Posting of the same content is not allowed

These are the three points. This time, I will validate the case where it is 1 to 30 characters.

Check form data class

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.

Editing controller class

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 theBindingResult 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.

Display the error details on 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.

Screen Shot 0002-11-07 at 20.44.33.png

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

Let's create a TODO application in Java 13 TODO form validation 1: Character limit ・ Gradle update to use @Validated
Let's create a TODO application in Java 4 Implementation of posting function
Let's create a TODO application in Java 6 Implementation of search function
Let's create a TODO application in Java 8 Implementation of editing function
Let's create a TODO application in Java 1 Brief explanation of MVC
Let's create a TODO application in Java 5 Switch the display of TODO
Let's create a TODO application in Java 9 Create TODO display Sort by date and time + Set due date default to today's date
Let's create a TODO application in Java 2 I want to create a template with Spring Initializr and make a Hello world
Let's create a TODO application in Java 11 Exception handling when accessing TODO with a non-existent ID
How to create a new Gradle + Java + Jar project in Intellij 2016.03
Let's create a TODO application in Java 3 Save temporary data in MySQL-> Get all-> Display on top
Create a TODO app in Java 7 Create Header
Try to create a bulletin board in Java
Let's make a calculator application with Java ~ Create a display area in the window
How to create a Java environment in just 3 seconds
I tried to create a Clova skill in Java
How to create a data URI (base64) in Java
Create a Java Servlet and JSP WAR file to deploy to Apache Tomcat 9 in Gradle
How to create a placeholder part to use in the IN clause
Create a method to return the tax rate in Java
[Java] How to use substring to cut out a character string
How to simulate uploading a post-object form to OSS in Java
Study Java: Use Timer to create something like a bomb timer
Create a simple DRUD application with Java + SpringBoot + Gradle + thymeleaf (1)
[Enum_help] Use enum_help to create a select box displayed in Japanese!
Preparing to create a Rails application
Let's use Twilio in Java! (Introduction)
[Java] How to create a folder
How to use classes in Java?
To create a Zip file while grouping database search results in Java
[Java] How to use substring to cut out a part of a character string
I tried to make a talk application in Java using AI "A3RT"
Volume of trying to create a Java Web application on Windows Server 2016
Multilingual Locale in Java How to use Locale
A memo to simply create a form using only HTML and CSS in Rails 6
Let's create a versatile file storage (?) Operation library by abstracting file storage / acquisition in Java
[Azure] I tried to create a Java application for free-Web App creation- [Beginner]