Thymeleafでセレクトボックス(select)の初期値を設定

Thymeleafでセレクトボックス(select)の初期値を設定

Thymeleafでセレクトボックスの初期値を設定する方法を以下に示します。

コントローラの処理

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class SelectBoxController {

  @GetMapping("/select")
  public String showForm(Model model) {
    model.addAttribute("selectedValue", "2"); // 初期値を設定
    return "selectForm";
  }

  @PostMapping("/select")
  public String processForm(@RequestParam("selectedValue") String selectedValue, Model model) {
    model.addAttribute("selectedValue", selectedValue);
    return "selectForm";
  }
}

HTML (Thymeleafテンプレート)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>セレクトボックスの初期値設定</title>
</head>
<body>
  <form action="#" th:action="@{/select}" th:object="${selectedValue}" method="post">
    <label for="selectBox">選択してください:</label>
    <select id="selectBox" name="selectedValue">
      <option th:value="1" th:text="'Option 1'" th:selected="${selectedValue == '1'}">Option 1</option>
      <option th:value="2" th:text="'Option 2'" th:selected="${selectedValue == '2'}">Option 2</option>
      <option th:value="3" th:text="'Option 3'" th:selected="${selectedValue == '3'}">Option 3</option>
    </select>
    <button type="submit">送信</button>
  </form>

  <p th:if="${selectedValue != null}">選択された値: <span th:text="${selectedValue}"></span></p>
</body>
</html>

このコードでは、showFormメソッドでセレクトボックスの初期値を設定しています。
HTMLテンプレートでは、th:selected属性を使用して、初期値が選択された状態になるようにしています。
フォームが送信されると、選択された値が再度表示されます。