(4) 動的WEBページの作成 [Thymeleaf]
はじめに
今回はいよいよ画面の内容が変化する動的WEBページを作成します。
今回作成する内容
概要
2つの値の足し算を行うWEBページです。
画面
作成手順
1. 計算画面(calc.html)の作成
ポイント
- 計算を行う画面(calc.html)を作成する
- Thymeleafのタグを使って入力項目(値1、値2)と結果を表示する項目を定義する
calc.html
<!DOCTYPE html> <html lang="ja" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"/> <title>calc</title> </head> <body> <h3>WEBプログラミング入門 計算ページ</h3> <form th:action="@{/calc}" method="POST" th:object="${form}"> <input type="text" th:field="*{val1}" /> + <input type="text" th:field="*{val2}" /> = <span th:text="${ans}"></span> <br/><br/> <input type="submit" value="計算" /> </form> </body> </html>
2. 計算画面で使用するformクラス(CalcForm.java)の作成
クラス作成画面表示
クラスを作成
- formパッケージに「CalcForm」という名前でクラスを作成
作成されたクラス
- クラスが作成される(中身は空っぽ)
アクセサ作成画面表示
- 入力項目の値1(val1)と値2(val2)を作成
- アクセサ(getter/setter)をEclipseの機能で作成
アクセサ作成
- アクセサを作成する項目にチェックを入れて「OK」をクリック
作成されたアクセサ
- アクセサが作成されて「CalcForm.java」作成完了
3. コントローラークラス(AppController.java)に計算処理を追加
ポイント
- calc処理を追加
- 入力された値1と値2の加算結果を画面表示項目にセット
AppController.java
package com.sbc.web; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import com.sbc.web.form.CalcForm; @Controller public class AppController { @RequestMapping("/") public String index(){ return "index"; } @RequestMapping("/second") public String second(){ return "second"; } // ↓↓↓ 以下の処理を追加 ↓↓↓ @RequestMapping("/calc") public String calc(@ModelAttribute CalcForm form, Model model){ //-------------------------------------- // 値1と値2を足した結果を算出する //-------------------------------------- String ans = null; try{ // 入力された値1・値2を数値に変換 int val1 = convertToNumber(form.getVal1()); int val2 = convertToNumber(form.getVal2()); // 計算(足し算) int result = val1 + val2; // 結果を文字列に変換 ans = String.valueOf(result); } catch(Exception e){ ans = "入力された値が正しくありません。整数を入力してください"; } //-------------------------------------- // 画面表示項目設定 //-------------------------------------- // 画面に渡す値を設定 model.addAttribute("form", form); model.addAttribute("ans", ans); // calc画面を表示 return "calc"; } /** * 文字列を数値に変換する * * @param val 文字列 * @return 数値 */ private int convertToNumber(String val){ // 値が空の場合はゼロを返却 if(StringUtils.isEmpty(val)){ return 0; } // 数値に変換した値を返却 return Integer.parseInt(val); } }
動作確認
以上で完成したので動かして確認します
アプリを起動
画面表示
- ブラウザでURL「http://localhost:8080/calc」を表示
計算実行
- 値1と値2に値を入力し「計算」ボタンをクリックする
結果表示
おわりに
処理自体は単純ですが動的WEBページを作成できました。
次回からいろいろなバリエーションのページを作成していきます。