9
10

More than 5 years have passed since last update.

Spring Bootのバリデーションメッセージの変更

Last updated at Posted at 2017-12-13

はじめに

spring bootでバリデーションチェックをアノテーションで行った際のメッセージを変更する備忘録です

環境情報

Spring Boot 1.5.4(Maven)

ソース

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";
        }

        //ログイン処理
        ......

        return "redirect:/menu/index";
    }
}
LoginForm.java
public class LoginForm extends BaseForm {

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

    /* thymeleafで使用する為にgetter/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>ログイン</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">ユーザーID</label>
                <div class="col-sm-5">
                    <input type="text" class="form-control" id="user-id" th:field="*{userId}" placeholder="ユーザー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">パスワード</label>
                <div class="col-sm-5">
                    <input type="password" class="form-control" id="password" th:field="*{password}" placeholder="パスワード" />
                </div>
            </div>
            <div class="form-group">
                <input type="submit" class="btn btn-primary col-sm-2 col-sm-offset-2" name="login" value="ログイン" />
                <input type="reset" class="btn btn-default col-sm-2 col-sm-offset-1" name="clear" value="クリア" />
            </div>
        </form>
    </div>
</body>
</html>

次にWebMvcConfigurerAdapterを継承したクラスを作成する
メッセージがデフォルトではUTF-8に対応していないらしいので、
エンコードを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のメッセージをUTF-8で管理します。
     * @return
     */
    @Bean(name = "messageSource")
    public MessageSource messageSource()
    {
        ReloadableResourceBundleMessageSource bean = new ReloadableResourceBundleMessageSource();
        bean.setBasename("classpath:ValidationMessages");
        bean.setDefaultEncoding("UTF-8");
        return bean;
    }

}

次にバリデーションメッセージを記載するpropertiesファイルをresourceフォルダ直下に作成する
ファイル名はAppConfigurerAdapter.javaで指定したファイル名にすること
メッセージのKeyはアノテーションのフルネームを指定する。
メッセージの{0}にはフィールド名が入る
フィールド名に別名を付けたい場合はフィールド名も設定する

ValidationMessages.properties
#メッセージ
org.hibernate.validator.constraints.NotEmpty.message={0}を入力してください。

#フィールド名
userId=ユーザーID
password=パスワード

実行してみる

ログイン画面でユーザーIDとパスワードを未入力でログインボタンを押下した結果です。
login.png

9
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10