データベースからの検索結果を List<Result> result; の形で取得できたとして
java
1import java.util.ArrayList;
2import java.util.List;
3
4import org.springframework.stereotype.Controller;
5import org.springframework.web.bind.annotation.GetMapping;
6import org.springframework.web.bind.annotation.RequestMapping;
7import org.springframework.web.servlet.ModelAndView;
8
9@Controller
10@RequestMapping("list")
11public class ListController {
12
13 @GetMapping
14 public ModelAndView select(ModelAndView mnv) {
15 List<Result> results = new ArrayList<Result>() {{
16 add(new Result("alpha", "addressA"));
17 add(new Result("beta", "addressB"));
18 add(new Result("charlie", "addressC"));
19 }};
20
21 mnv.addObject("results", results);
22 mnv.addObject("select", "beta");
23 mnv.setViewName("list");
24 return mnv;
25 }
26
27 public static class Result {
28
29 public Result(String name, String address) {
30 this.name = name;
31 this.address = address;
32 }
33 private String name;
34 private String address;
35 public String getName() {
36 return name;
37 }
38 public void setName(String name) {
39 this.name = name;
40 }
41 public String getAddress() {
42 return address;
43 }
44 public void setAddress(String address) {
45 this.address = address;
46 }
47 }
48}
この結果をうけて、セレクトボックスを表示するThymeleafは以下のようになります。
html
1<!DOCTYPE html>
2<html xmlns:th="http://www.thymeleaf.org">
3<head>
4 <meta charset="UTF-8" />
5 <title>Title</title>
6</head>
7<body>
8<select id="select">
9 <option th:each="result : ${results}" th:value="${result.name}" th:selected="${result.name == select}">[[${result.name}]]</option>
10</select>
11</body>
12</html>