[Java] [Java] Articles on adding validation with Spring Boot 2.3.1

4 minute read

Introduction

Hello! This is the 4th installment of the Java Play Series from scratch. I just named it.

Click here for previous articles ↓

  1. Construction of STS environment on mac
  2. Spring Boot Hello World
  3. Create echo application with Spring Boot

This time, I’ll add validation to the echo application I made last time.

Momomoto.gif

Currently, as many characters as characters, numbers and environment-dependent characters can be entered, sending a mysterious document causes the display to collapse as shown below.

Screenshot 2020-07-21 0.26.28.png

scared. When Hatena is lined up in the name, it creates a disturbing atmosphere. Is it garbled? I don’t like the fact that Zero breaks through the screen width.

Therefore, this time, I’d like to validate with the following requirements, like the user name of some service. In the case of an error, it is an image that displays an error message on the same screen.

  • Characters that can be used: Only half-width alphanumeric characters
  • Character limit: 4 characters or more

The finished product looks like this: (I changed the background color to a color that is easy on the eyes)

Screen capture 2020-07-21 23.39.15.mov.gif

Usage environment and version

  • macOS Catalina
  • jdk14.0.1
  • JUnit5
  • Maven 3.6.3_1
  • STS 4.6.1
  • Spring Boot 2.3.1
  • spring-boot-starter-thymeleaf-2.3.1

Implement validation by annotation in form class

The following annotations have been added to the form class.

  • @NotBlank: You can check 1 that it is not null or empty string
  • @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

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 on error to controller class

Only write 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 part that the framework is responsible for, so there is no need to implement them. (From Spring thorough introduction)
  • Added branch on error. If an error occurs in the check using annotations, we do not want to go to the “Hello ${username}” screen, so we have changed it so that the same page is returned.

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 on error to index.html

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

Screenshot 2020-07-21 23.26.59.png

Since the form object is already bound last time, I can get the error information of echoForm and pop it into Thymeleaf to make 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 an error 2. Specifically, because the property of the form object is set in the th:errors attribute, only the error message for the specified property will be displayed. If there are multiple error messages, <br /> is automatically entered. Thank you.

index.html


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

Localization of error wording

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

Screenshot 2020-07-21 23.52.09.png

This is a bit disgusting…I could pass it with a stylish error message ❤️, but it is unclear from the user’s perspective regarding the size number… Let’s fix the error message in Japanese here!

It seems that it is desirable to define Bean Validation error message by Spring MVC in 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.

Screenshot 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=Required field.
javax.validation.constraints.Size.message=Must be at least 4 characters.
javax.validation.constraints.Pattern.message=Only single-byte alphanumeric characters are valid.

By the way, if you just paste the above into ValidationMessages.properties, it will automatically become the following by just inputting Japanese and pressing enter… Since 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 this Qiita, I’m also Spring 2 and Java 11 or above. 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 the default to UTF-8.

Screenshot 2020-07-22 0.58.50.png

When I try to save the file with this, the following warning appears, but Save as UTF-8 worked without problems.

Screenshots 2020-07-22 0.50.06.png

Now you have a Japanese message as below!

Screenshot 2020-07-22 0.41.48.png

in conclusion

This time, I had a bit of trouble with the Thymeleaf notation for the text addition part at the time of error and Japaneseization of ValidationMessages.properties! The method introduced this time is suspicious if it is Spring 1, so please check it appropriately.

Thank you for reading!

  1. use @NotNull to check only null 

  2. I referred to the implementation of this page