「Spring Boot」thymeleafでフォームの入力値を別画面に送信する
1.依存関係ライブラリを追加
pom.xml 下記を追記
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.入力フォーム
ファイルパス:src\main\resources\templates\user\index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<title>ユーザの新規登録 入力フォーム</title>
</head>
<body>
<!--送信先dispform -->
<form method="get" th:action="@{/dispform}">
ユーザー名: <input type="text" name="username" /><br/>
パスワード: <input type="text" name="pwd" /><br/>
<input type="submit" value="登録" />
</form>
</body>
</html>
3.コントローラの定義
package com.arkgame.study;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
//アノテーションController
@Controller
public class SampleController {
// 送信先user
@GetMapping("/user")
public String createUser() {
return "user/index";
}
// 送信先dispform
@GetMapping("/dispform")
public String Input(@RequestParam(name = "username") String username, @RequestParam(name = "pwd") String pwd,
Model model) {
// 変数username、pwdをモデルに保存
model.addAttribute("userInfo", "入力したユーザ名:" + username + " 入力したパスワード:" + pwd);
// userフォルダ配下のdispform.htmlを表示
return "user/dispform";
}
}
4.フォームの値を表示
ファイルパス:src\main\resources\templates\user\dispform.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<title>ユーザーの入力情報を表示 フォームの項目の値を表示</title>
</head>
<body>
<div th:text="${userInfo}"></div>
</body>
</html>
5.application.properties
server.port =8788
6.動作テスト
http://127.0.0.1:8788/user
ユーザ名:testuser
パスワード:testpwd
「登録」ボタンを押下すると、次画面に遷移する
http://127.0.0.1:8788/dispform?username=testuser&pwd=testpwd
結果
入力したユーザ名:testuser 入力したパスワード:testpwd