Spring Boot validation message changes

Introduction

It is a memorandum to change the message when validation check is performed with annotation in spring boot

Environmental information

Spring Boot 1.5.4(Maven)

Source

Create Controller, Form, View

LoginController.java


@Controller
@RequestMapping({"/", "/login"})
public class LoginController extends BaseController {

	@ModelAttribute
	public LoginForm initForm(){
		return new LoginForm();
	}

	@RequestMapping(value = {"/index", "/"}, method = RequestMethod.GET)
	public String index(Model model){
		return "test/index";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(@ModelAttribute @Validated TestForm form, BindingResult result, Model model)
	{
		if(result.hasErrors()){
			return "test/index";
		}

		//Login process
		......

		return "redirect:/menu/index";
	}
}

LoginForm.java


public class LoginForm extends BaseForm {

	@NotEmpty
	public String userId;
	@NotEmpty
	public String password;

	/*Getter for use with thymeleaf/need setter*/
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

}

login/index.html


<!DOCTYPE html>
<html
	xmlns        = "http://www.w3.org/1999/xhtml"
	xmlns:th     = "http://www.thymeleaf.org"
	xmlns:layout = "http://www.ultraq.net.nz/thymeleaf/layout"
	layout:decorator="layout"
>
<head>
	<title>Login</title>
</head>
<body>
	<div layout:fragment="contents">
		<form class="form-horizontal" method="POST" action="/login/login/" th:action="@{/login/login}" th:object="${loginForm}">
			<div class="form-group">
				<p th:if="${#fields.hasErrors('*{userId}')}" th:errors="*{userId}" class="col-sm-offset-2 text-danger"></p>
				<label for="user-id" class="col-sm-2 control-label">User ID</label>
				<div class="col-sm-5">
					<input type="text" class="form-control" id="user-id" th:field="*{userId}" placeholder="User ID" />
				</div>
			</div>
			<div class="form-group">
				<p th:if="${#fields.hasErrors('*{password}')}" th:errors="*{password}" class="col-sm-offset-2 text-danger"></p>
				<label for="password" class="col-sm-2 control-label">password</label>
				<div class="col-sm-5">
					<input type="password" class="form-control" id="password" th:field="*{password}" placeholder="password" />
				</div>
			</div>
			<div class="form-group">
				<input type="submit" class="btn btn-primary col-sm-2 col-sm-offset-2" name="login" value="Login" />
				<input type="reset" class="btn btn-default col-sm-2 col-sm-offset-1" name="clear" value="clear" />
			</div>
		</form>
	</div>
</body>
</html>

Next, create a class that inherits WebMvcConfigurerAdapter It seems that the message does not support UTF-8 by default, so Set the encoding to UTF-8

AppConfigurerAdapter.java


@Configuration
public class AppConfigurerAdapter extends WebMvcConfigurerAdapter {

	@Bean(name="validator")
	public LocalValidatorFactoryBean localValidatorFactoryBean() {
		LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
		localValidatorFactoryBean.setValidationMessageSource(messageSource());
		return localValidatorFactoryBean;
	}

	/**
	 *Validation message UTF-Manage with 8.
	 * @return
	 */
	@Bean(name = "messageSource")
	public MessageSource messageSource()
	{
		ReloadableResourceBundleMessageSource bean = new ReloadableResourceBundleMessageSource();
		bean.setBasename("classpath:ValidationMessages");
		bean.setDefaultEncoding("UTF-8");
		return bean;
	}

}

Next, create a properties file that describes the validation message directly under the resource folder. The file name should be the file name specified in ʻAppConfigurerAdapter.java. The Key of the message specifies the full name of the annotation. The field name is entered in {0}` of the message If you want to give an alias to the field name, also set the field name

ValidationMessages.properties


#message
org.hibernate.validator.constraints.NotEmpty.message={0}Please enter.

#Field name
userId=User ID
password=password

Try to run

This is the result of pressing the login button without entering the user ID and password on the login screen. login.png

Recommended Posts

Spring Boot validation message changes
Major changes in Spring Boot 1.5
Going out of message (Spring boot)
Get validation results with Spring Boot
Message cooperation started with Spring Boot
[Introduction to Spring Boot] Form validation check
Challenge Spring Boot
Changes when migrating from Spring Boot 1.5 to Spring Boot 2.0
Changes when migrating from Spring Boot 2.0 to Spring Boot 2.2
Spring Boot Form
Spring Boot Memorandum
gae + spring boot
Form class validation test with Spring Boot
[FCM] Implementation of message transmission using FCM + Spring boot
[Java] Article to add validation with Spring Boot 2.3.1.
SPRING BOOT learning record 01
Spring Boot + Heroku Postgres
Spring boot memo writing (1)
First Spring Boot (DI)
Spring Boot2 cheat sheet
Spring Boot Servlet mapping
Spring Boot learning procedure
Spring boot memo writing (2)
[Spring Boot] DataSourceProperties $ DataSourceBeanCreationException
Self-made Validation with Spring
Spring Boot 2.3 Application Availability
Spring boot tutorials Topics
Download with Spring Boot
Message cooperation started with Spring Boot Apache Kafka edition
[JUnit 5] Write a validation test with Spring Boot! [Parameterization test]
[Spring Boot] Environment construction (macOS)
Set context-param in Spring Boot
Try Spring Boot from 0 to 100.
Generate barcode with Spring Boot
Spring validation and error code
Hello World with Spring Boot
Spring Boot on Microsoft Azure
Implement GraphQL with Spring Boot
Get started with Spring boot
[Spring Boot] Move validation (@Validated / @Valid) at any time [Bean Validation]
Hello World with Spring Boot!
Spring Boot 2 multi-project in Gradle
[Spring Boot] Web application creation
spring boot port duplication problem
Run LIFF with Spring Boot
SNS login with Spring Boot
Spring Boot Hot Swapping settings
[Java] Thymeleaf Basic (Spring Boot)
Introduction to Spring Boot ① ~ DI ~
File upload with Spring Boot
Spring Boot starting with copy
CICS-Run Java application-(4) Spring Boot application
Spring Boot starting with Docker
Spring Boot + Springfox springfox-boot-starter 3.0.0 Use
Spring Boot DB related tips
Hello World with Spring Boot
Set cookies with Spring Boot
[Spring Boot] Easy paging recipe
Use Spring JDBC with Spring Boot
Docker × Spring Boot environment construction
Add module with Spring Boot