teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

ControllerとThymeleafテンプレートの実装例を追記。

2020/07/29 10:26

投稿

A-pZ
A-pZ

スコア12011

answer CHANGED
@@ -1,1 +1,51 @@
1
- [Thymeleafでセレクトボックスを使う](https://qiita.com/alpha_pz/items/e5d1872fbb8f2b3d3f3d) が参考になるでしょうか。
1
+ [Thymeleafでセレクトボックスを使う](https://qiita.com/alpha_pz/items/e5d1872fbb8f2b3d3f3d) が参考になるでしょうか。
2
+
3
+ 例えば、月を入力させたいのであれば、
4
+
5
+ Controllerの実装:
6
+
7
+ ```java
8
+ import java.util.Arrays;
9
+ import java.util.List;
10
+
11
+ import org.springframework.stereotype.Controller;
12
+ import org.springframework.web.bind.annotation.GetMapping;
13
+ import org.springframework.web.bind.annotation.RequestMapping;
14
+ import org.springframework.web.servlet.ModelAndView;
15
+
16
+ @Controller
17
+ @RequestMapping("wheel")
18
+ public class SampleController {
19
+ @GetMapping("")
20
+ public ModelAndView display(ModelAndView mnv) {
21
+
22
+ List<Integer> months = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
23
+ mnv.addObject("targetMonth", 7);
24
+ mnv.addObject("months", months);
25
+ mnv.setViewName("wheel");
26
+ return mnv;
27
+ }
28
+
29
+ }
30
+ ```
31
+
32
+ ここから表示する wheel.html にて、Controllerで定義した years の内容を繰り返し表示する方法は、
33
+ ※ targetMonth は 初期表示させる月の値
34
+
35
+ ```html
36
+ <!DOCTYPE html>
37
+ <html xmlns:th="http://www.thymeleaf.org">
38
+ <head>
39
+ <meta charset="UTF-8">
40
+ <title>Insert title here</title>
41
+ </head>
42
+ <body>
43
+ <select name="month">
44
+ <option th:each="month : ${months}"
45
+ th:value="${month}"
46
+ th:selected="${month == targetMonth}"
47
+ th:text="${month}"></option>
48
+ </select>
49
+ </body>
50
+ </html>
51
+ ```