0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

オブジェクトを使ってビューとコントローラの値を共有

Last updated at Posted at 2023-10-22

目的

Spring Bootのビュー→コントローラ、コントローラ→ビューの値の共有をオブジェクトを使って実行することで、オブジェクトの理解を深める。

作成するもの

Spring Bootを使って作成する
/thymeleaf-inputPageにアクセスすると、入力画面が表示される。
入力画面で名前、年齢入力すると、出力画面が表示される。
MVCを使用し、入力画面と出力画面の間にはコントローラを挟む
画面とコントローラ間のデータはオブジェクトを使用する。

ファイル一覧

  • コントローラ、オブジェクト
    ThymeleafController.java
  • 入力画面
    thymeleaf-inputPage.html
  • 出力画面
    thymeleaf-outputPage.html
ThymeleafController.java
//import省略
@Controller
public class ThymeleafController {

	@GetMapping(path = "/thymeleaf-inputPage")
	public String thymeleafIn(Model model) { 
		User user = new User();
		model.addAttribute("userInput", user);
		return "thymeleaf-inputPage";
	}
	
	@PostMapping(path = "/thymeleaf-outputPage")
	public String thymeleafOut(@ModelAttribute("userInput") User user, Model model) {
		model.addAttribute("userOutput", user);
		return "thymeleaf-outputPage";
	}
}

//Userクラスの設定
class User{

	private String name;
	private String age;

    //getter,setter省略
}
thymeleaf-inputPage.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head> 
    <title>Thymeleaf test</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <h1>入力画面です</h1> 
    <form th:action="@{/thymeleaf-outputPage}" method="post" th:object="${userInput}">
		<p>名前</p>
		<input type="text" th:field="*{name}"/>
		<p>年齢</p>
		<input type="text" th:field="*{age}"/>
		<input type="submit" value="出力画面へ"/>
	</form>
</body>
</html>
thymeleaf-outputPage.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head> 
    <title>Thymeleaf test</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <h1>出力画面です</h1> 
    <div th:object="${userOutput}">
    	<p>名前</p>
		<p th:text="*{name}"></p>
		<p>年齢</p>
		<p th:text="*{age}"></p>
	</div>
</body>
</html>

解説

入力画面にアクセス

/thymeleaf-inputPageのページをURLに指定してアクセスするとコントローラーのthymeleafInメソッドが実行される。引数のModel modelはビューに値を共有するためのインスタンスである。

ThymeleafController.javaのthymeleafInメソッド抜粋
	@GetMapping(path = "/thymeleaf-inputPage")
	public String thymeleafIn(Model model) { 
		User user = new User();
		model.addAttribute("userInput", user);
		return "thymeleaf-inputPage";
	}

Userクラスのフィールドにはname,ageがある。
ビューでuserを使うためmodel.addAttribute("userInput", user);modeluserInput=userを代入する。
return "thymeleaf-inputPage";で出力画面のthymeleaf-inputPage.htmlが表示される。

入力画面

入力画面(thymeleaf-inputPage.html)ではth:fieldでuserOutputの変数を使用しているので入力欄にはname,ageの値が表示されるが、画面を表示したタイミングではuserのフィールド(nameとage)は値が入っていないため、入力欄には何も表示されない。
image.png

値を入力してボタンを押す

ここでは名前に「テスト太郎」、年齢に「30」を入れてボタンを押した。
image.png

出力画面へ

名前、年齢を入力して出力画面へボタンを押すと、入力内容はオブジェクトの変数に格納された状態でコントローラに渡される。

ThymeleafController.javaのthymeleafOutメソッド抜粋
	@PostMapping(path = "/thymeleaf-outputPage")
	public String thymeleafOut(@ModelAttribute("userInput") User user, Model model) {
		model.addAttribute("userOutput", user);
		return "thymeleaf-outputPage";
	}

コントローラでは@ModelAttribute("userInput") User userのコードで入力画面から受け取ったuserInputをUserクラスの変数userに格納している。
model.addAttribute("userOutput", user);でmodelにuserOutput=userを格納し、ビュー側でuserデータを使えるようにする。
return "thymeleaf-outputPage";thymeleaf-outputPage.htmlの画面を表示。
image.png

出力画面へ 補足

returnが返される直前の状態をデバッグ機能で確認すると次の状態になっている
image.png
modelにはuserOutputとしてuserInputデータのage,nameが格納されていることが確認できるが、@ModelAttributeで指定したuserInputがmodelに格納されている事も確認できる。
フォームデータをそのまま出力する事はないと思われるが、出力画面でuserInputのオブジェクトも使用できる。

まとめ

コントローラーのmodelにオブジェクトを格納すると、ビューのThymeleafを使ってmodelに入れたオブジェクトが使える。
ビューのタグ内でth:field""にオブジェクトを指定すると、コントローラ側でそのオブジェクトが共有される。ビュー側でオブジェクトを使うには、メソッドの引数に@ModelAttribute("オブジェクト名") オブジェクトの型 メソッド内で使うインスタンス名を指定すればよい。

参考

コントローラのコードは次のページの「5.5.11 選択オブジェクトへの変数式」を参考にしました

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?