Thymeleafでラジオボタン(radio)の初期値を設定
Thymeleafでラジオボタンの初期値を設定する方法について説明します。
以下に、ラジオボタンの初期値設定と、コントローラの処理を含むソースコードの例を示します。
1. フォームのHTML (Thymeleafテンプレート)
<form action="#" th:action="@{/submit}" th:object="${form}" method="post"> <label> <input type="radio" th:field="*{option}" value="option1" /> オプション1 </label> <label> <input type="radio" th:field="*{option}" value="option2" /> オプション2 </label> <label> <input type="radio" th:field="*{option}" value="option3" /> オプション3 </label> <button type="submit">送信</button> </form>
2. フォームクラス
public class MyForm { private String option; // ゲッターとセッター public String getOption() { return option; } public void setOption(String option) { this.option = option; } }
3. コントローラ
@Controller public class MyController { @GetMapping("/form") public String showForm(Model model) { MyForm form = new MyForm(); // 初期値を設定 form.setOption("option2"); model.addAttribute("form", form); return "form"; } @PostMapping("/submit") public String submitForm(@ModelAttribute MyForm form, Model model) { // 送信されたデータを処理 String selectedOption = form.getOption(); model.addAttribute("selectedOption", selectedOption); return "result"; } }
4. 結果表示用HTML (Thymeleafテンプレート)
<p>選択されたオプション: <span th:text="${selectedOption}"></span></p>
この例では、ラジオボタンの初期値として「オプション2」を設定しています。
MyControllerのshowFormメソッドでMyFormオブジェクトのoptionプロパティに初期値を設定し、テンプレートで表示するようにしています。