LoginSignup
0
2

More than 3 years have passed since last update.

【Java・SpringBoot・Thymeleaf】エラーメッセージを実装(SpringBootアプリケーション実践編3)

Last updated at Posted at 2020-11-23

ログインをして、ユーザー一覧を表示するアプリケーションを作成し、
Springでの開発について勉強していきます🌟
前回のデータバインドに引き続きバインド失敗時のエラーメッセージを実装します

前回の記事🌟
【Java・SpringBoot・Thymeleaf】データバインド(SpringBootアプリケーション実践編2)

エラーメッセージを実装

  • src/main/resouces配下にmessages.propertiesというファイルを作成
  • その内に、各フィールドに対応するメッセージを設定する

パターン1

  • typeMismatch.<ModelAttributeのキー名>.<フィールド名>=<エラーメッセージ>
src/main/resources/messages.properties
typeMismatch.signupForm.age=数値を入力してください
typeMismatch.signupForm.birthday=yyyy/MM/dd形式で入力してください

パターン2

  • typeMismatch.<フィールド名>=<エラーメッセージ>
  • 複数のオブジェクトでageやbirthdayというフィールド名を使っていた場合、すべてにメッセージが適用される
src/main/resources/messages.properties
typeMismatch.age=数値を入力してください(パターン2)
typeMismatch.birthday=yyyy/MM/dd形式で入力してください(パターン2)

パターン3

  • typeMismatch.<フィールドのデータ型>=<エラーメッセージ>
  • 同じデータ型にメッセージが適用される
src/main/resources/messages.properties
typeMismatch.int=数値を入力してください(パターン3)
typeMismatch.java.util.Date=yyyy/MM/dd形式で入力してください(パターン3)

SpringBootを起動して、ログイン画面を確認!

  • http://localhost:8080/login
  • ユーザー登録ボタンをクリックするとログイン画面に遷移
  • プロパティファイルを作成後、エラー文字列を入れると作成したエラーメッセージが表示されましたo(^_^)o
  • 次回はメッセージプロパティファイルを複数用意して切り替える方法を実践します🌟

修正後エラー.png

0
2
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
0
2