登録画面で「登録」ボタンを押した後、
バリデーションで引っ掛かってエラーになっても
入力内容を画面に保持して置く方法についてです。
テンプレートエンジンは、Tymeleafを使用しています。
方法としては、「th:field」を使って入力したフォームのフィールド名を指定するだけです。
目次
コード
①入力するフォームクラスを、th:object で指定し、
ユーザID(Email)の入力ボックスに、th:field でフィールド名を指定します。
1 2 3 4 5 |
<form method="post" th:action="@{/signup}" th:object="${signupForm}"> <div class="form-group" th:classappend="${#fields.hasErrors('userId')} ? 'has-error'"> <input type="text" th:field="*{userId}" placeholder="email@address.com"> <span class="text-danger" th:if="${#fields.hasErrors('userId')}" th:errors="*{userId}"></span> </div> |
②登録時にエラーだった場合、formとmodelを登録画面に戻すようにします。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
//登録ボタン押下時のイベント @PostMapping("/signup") public String postSignup(@ModelAttribute SignupForm form, BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) { return getSignup(form, model); } // 画面表示とエラー時に戻す画面 @GetMapping("/signup") public String getSignup(@ModelAttribute SignupForm form, Model model) { return "login/signup"; } |
実装後の動作
ユーザID以外の項目がバリデーションエラーになったため登録画面に戻されますが、
ユーザIDに入力した値は保持されています。