[Spring Boot2.4.2] Thymeleafを使って値を渡す

pomにdependenciesを追加する

1
2
3
4
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

src/main/resources/templates/test1/testform.html

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>submit</title>
</head>
<body>
<form method="get" action="testform">
<input type="text" name="text1">
<input type="submit" value="送信ボタン">
</form>
</body>
</html>

com.example.demo/MainController.java
L @RequestParamはリクエストされたパラメータを受け取り、変数str1にsetする
L addAttributeで変数str1をセット

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.example.demo;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
 
@Controller
@RequestMapping("/test1")
public class MainController {
     
    @GetMapping
    public String input1() {
        return "test1/index";
    }
     
    @GetMapping("testform")
    public String output1(
            @RequestParam(name = "text1") String str1,
            Model model) {
            model.addAttribute("moji1", str1);
            return "test1/testform";
    }
     
}

src/main/resources/templates/test1/index.html

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>submit</title>
</head>
<body>
<p th:text="${moji1}"></p>
 
</body>
</html>

上手くいかないが、何故上手くいかないのかよくわからん。