[Java] Article to add validation with Spring Boot 2.3.1.

Introduction

Hello! This is the 4th series to play with Java from scratch. I just named it.

Click here for articles up to the last time ↓

  1. Building STS environment on mac
  2. Hello World with Spring Boot
  3. Create Echo Application with Spring Boot

This time, I would like to add validation to the echo application I made last time.

もょもと.gif

Currently, character strings, numbers, and environment-dependent characters can be entered in any number of characters, so if you send a phantom document, the display will be corrupted as shown below.

スクリーンショット 2020-07-21 0.26.28.png

scared. If Hatena is lined up in the name, it will create a disturbing atmosphere. Is it garbled? I don't like the fact that Zero has broken through the screen width.

So, this time, I'm going to validate with the following requirements, like the user name of some service. In case of an error It is an image that an error message is displayed on the same screen.

--Available character types: Half-width alphanumeric characters only --Character limit: 4 characters or more

The finished product has the following shape. (The background color has been changed to a color that is easy on the eyes)

画面収録 2020-07-21 23.39.15.mov.gif

Usage environment and version

Implement validation with annotation in form class

The following annotations have been added to the form class.

--@NotBlank: You can check that it is not null or empty string [^ 1] --@Size: You can specify the minimum and maximum values using the attribute min or max. --@Pattern: You can specify a regular expression pattern string with the attribute value regexp. This time I used a regular expression that allows only half-width alphanumeric characters

[^ 1]: Use @NotNull to check only null

EchoForm.java


package com.example.form;

import java.io.Serializable;

import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotBlank;

public class EchoForm implements Serializable {
    private static final long serialVersionUID = 1L;
    @NotBlank
    @Size(min = 4)
    @Pattern(regexp = "[a-zA-Z0-9]*") //Must be alphanumeric
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

Add branch to controller class in case of error

Write only the modified echo method. There are two changes below.

--Added BindingResult class to argument. BindingResult contains the input check result. Execution of input check and generation of BindingResult are the parts that the framework is responsible for, so there is no need to implement it. (From Introduction to Spring) --Added branch on error. If an error occurs in the check by annotation, I do not want you to go to the "Hello $ {username}" screen, so I am changing to return the same page.

EchoController.java


@RequestMapping(value = "echo", method = RequestMethod.POST)
	public String echo(@Validated EchoForm echoForm, BindingResult result, Model model) {
		if (result.hasErrors() ) {
			model.addAttribute("name", echoForm.getName());
			return "index";
		}
		model.addAttribute("name", echoForm.getName());
		return "echo";
	}

Add text to index.html in case of error

I want to display the error message in red as shown below only when an error occurs ... This can be done with Spring!

スクリーンショット 2020-07-21 23.26.59.png

Since we have already bound the form object last time, we can get the error information of echoForm and insert it into Thymeleaf to create HTML. Spring is amazing. Thymeleaf is amazing.

Only the form part is described. In the place surrounded by span, the error message is displayed only when the object is in error [^ 2]. Specifically, because the form object's properties are set in the th: errors attribute, only error messages for the specified properties are displayed. If there are multiple error messages, <br /> will be automatically entered. Thank you.

[^ 2]: I referred to the implementation of this page.

index.html


<form th:object="${echoForm}" th:action="@{/echo}" method="POST">
        <div>Please enter your username</div>
        <div>(4 or more half-width alphanumeric characters)</div>
        <div>
        	<input type="text" th:field="*{name}" /> 
        	<button>I will send</button>
        </div>
        <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}" style="color: red"></span>
</form>

Japanese localization of error wording

Actually, if you execute with the implementation so far, the error message will be the default message (English) of the annotation, so the error will be as follows.

スクリーンショット 2020-07-21 23.52.09.png

I don't like this a little ... The above may still be passed with a fashionable error message ❤️, but the size number is unclear to the user ... Let's fix this to a Japanese error message!

It seems desirable to define Bean Validation error messages by Spring MVC in the properties file. There seem to be several methods, but I chose that because it was easy to understand how to create ValidationMessages.properties directly under the classpath.

Create a new ValidationMessages.properties under resources.

スクリーンショット 2020-07-22 0.29.58.png

The content is a simple implementation that just rewrites the message of the annotation used.

ValidationMessages.properties


org.hibernate.validator.constraints.NotBlank.message=Input is required.
javax.validation.constraints.Size.message=Must be at least 4 characters.
javax.validation.constraints.Pattern.message=Only half-width alphanumeric characters are valid.

By the way, when I just pasted the above into ValidationMessages.properties, it automatically became as follows just by inputting Japanese and pressing enter ... Because the standard Bean of Spring Boot is not UTF-8 Multibyte It seems that the characters are garbled.

ValidationMessages.properties


org.hibernate.validator.constraints.NotBlank.message=\u5165\u529B\u5FC5\u9808\u3067\u3059\u3002
javax.validation.constraints.Size.message=4\u6587\u5B57\u4EE5\u4E0A\u3067\u306A\u304F\u3066\u306F\u3044\u3051\u307E\u305B\u3093\u3002
javax.validation.constraints.Pattern.message=\u534A\u89D2\u82F1\u6570\u306E\u307F\u6709\u52B9\u3067\u3059\u3002

As mentioned in the comment section of Qiita here, probably because I am also a Spring 2 system and Java 11 or higher, UTF in the file properties If I set it to -8, the application worked fine. Just right click on the file> Properties> Resource and change the Text file encoding from default to UTF-8.

スクリーンショット 2020-07-22 0.58.50.png

Now when I try to save the file I get the following warning, but it worked fine with Save as UTF-8.

スクリーンショット 2020-07-22 0.50.06.png

The message is now in Japanese as shown below!

スクリーンショット 2020-07-22 0.41.48.png

in conclusion

This time, I had a little trouble with the Thymeleaf notation of the text addition part at the time of error and the Japanese localization of ValidationMessages.properties! The method introduced this time is suspicious if it is Spring 1 system, so please check it as appropriate.

Thank you for reading!

Recommended Posts

[Java] Article to add validation with Spring Boot 2.3.1.
Get validation results with Spring Boot
Add Bean Validation with Micronaut (Java)
[Java] LINE integration with Spring Boot
[Introduction to Spring Boot] Form validation check
Form class validation test with Spring Boot
Add spring boot and gradle to eclipse
How to use MyBatis2 (iBatis) with Spring Boot 1.4 (Spring 4)
How to use built-in h2db with spring boot
Try to implement login function with Spring Boot
How to add a classpath in Spring Boot
Self-made Validation with Spring
Try to automate migration with Spring Boot Flyway
I wanted to gradle spring boot with multi-project
[Introduction to Spring Boot] Authentication function with Spring Security
Download with Spring Boot
Introduction to Java development environment & Spring Boot application created with VS Code
Settings for connecting to MySQL with Spring Boot + Spring JDBC
[Java] [Spring Boot] Specify runtime profile --Spring Boot starting with NetBeans
Automatically map DTOs to entities with Spring Boot API
[Java] How to omit spring constructor injection with Lombok
[JUnit 5] Write a validation test with Spring Boot! [Parameterization test]
How to boot by environment with Spring Boot of Maven
Attempt to SSR Vue.js with Spring Boot and GraalJS
Try Spring Boot from 0 to 100.
Generate barcode with Spring Boot
Hello World with Spring Boot
Java Config with Spring MVC
Implement GraphQL with Spring Boot
Java to play with Function
Get started with Spring boot
Run LIFF with Spring Boot
SNS login with Spring Boot
Introduction to Spring Boot ① ~ DI ~
File upload with Spring Boot
Spring Boot starting with copy
Introduction to Spring Boot ② ~ AOP ~
CICS-Run Java application-(4) Spring Boot application
Connect to DB with Java
Connect to MySQL 8 with Java
Using Mapper with Java (Spring)
Hello World with Spring Boot
Getting Started with Spring Boot
Introduction to Spring Boot Part 1
[Java] [Spring] Spring Boot 1.4-> 1.2 Downgrade Note
Create microservices with Spring Boot
Send email with spring boot
Spring Boot validation message changes
[Java / Kotlin] Escape (sanitize) HTML5 support with unbescape [Spring Boot]
Handle Java 8 date and time API with Thymeleaf with Spring Boot
[Java] Deploy the Spring Boot application to Azure App Service
Extract SQL to property file with jdbcTemplate of spring boot
How to call and use API in Java (Spring Boot)
Connect to database with spring boot + spring jpa and CRUD operation
Flow until output table data to view with Spring Boot
Domain Driven Development with Java and Spring Boot ~ Layers and Modules ~
I tried to get started with Swagger using Spring Boot
[Java] Sample project for developing web applications with Spring Boot
Spring Boot + Java + GitHub authentication login
Java to learn with ramen [Part 1]
Create an app with Spring Boot 2