条件分岐
ログインするWebサイトで、ログインしてない人に「ゲスト」と表示したり、ログインした人に「ようこそ〇〇さん!」のように表示するときに条件分岐を使用する。
テキストではp.180からの部分。
IndexController.java の最後にメソッドを追加する。
メソッド名、URL、HTMLテンプレートの名前を number にする。
@RequestMapping("/number/{id}")
public ModelAndView number(@PathVariable int id, ModelAndView mav) {
mav.setViewName("number");
mav.addObject("id", id);
mav.addObject("check", id >= 0);
mav.addObject("trueVal", "POSITIVE!");
mav.addObject("falseVal", "negative...");
return mav;
}
HTMLテンプレートで th:if と th:unless を使用して条件分岐する。
<body>
<h1>条件分岐</h1>
<p th:if="${check}" th:text="${id} + ' is ' + ${trueVal}">message.</p>
<p th:unless="${check}" th:text="${id} + ' is ' + ${falseVal}">message.</p>
</body>
switchを使って多項分岐する
月の値から季節を表示する。
IndexController.java に month() メソッドを追加する。
@RequestMapping("/month/{month}")
public ModelAndView month(@PathVariable int month, ModelAndView mav) {
mav.setViewName("month");
int m = Math.abs(month) % 12;
m = m == 0 ? 12 : m;
mav.addObject("month", m);
mav.addObject("check", Math.floor(m / 3));
return mav;
}
HTMLテンプレートは、month.html を追加する。
<body>
<h1>多項分岐</h1>
<div th:switch="${check}">
<p th:case="0" th:text="|${month} - Winter|"></p>
<p th:case="1" th:text="|${month} - Spring|"></p>
<p th:case="2" th:text="|${month} - Summer|"></p>
<p th:case="3" th:text="|${month} - Autumn|"></p>
<p th:case="4" th:text="|${month} - Winter|"></p>
</div>
</body>
th:eachで繰り返し表示する
IndexController.java に list() メソッドを追加する。
@RequestMapping("/list/")
public ModelAndView list(ModelAndView mav) {
mav.setViewName("list");
ArrayList<String[]> data = new ArrayList<>();
data.add(new String[] {"taro", "taro@yamada", "090-999-999"});
data.add(new String[] {"hanako", "hanako@flower", "080-888-888"});
data.add(new String[] {"sachiko", "sachiko@happy", "070-777-777"});
mav.addObject("data", data);
return mav;
}
list.html を追加する。
<body>
<h1>繰り返し</h1>
<table>
<tr>
<th>NAME</th>
<th>MAIL</th>
<th>TEL</th>
</tr>
<tr th:each="obj:${data}">
<td th:text="${obj[0]}"></td>
<td th:text="${obj[1]}"></td>
<td th:text="${obj[2]}"></td>
</tr>
</table>
</body>
JavaScript のインライン処理
Webサイトを作っていると、コントローラからJavaScriptに値を渡したいことがあるので、そのやり方を試してみる。
InddexController.java に tax() メソッドを追加する。
@RequestMapping("/tax/{tax}")
public ModelAndView tax(@PathVariable int tax, ModelAndView mav) {
mav.setViewName("tax");
mav.addObject("tax", tax);
return mav;
}
tax.html を作成する。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>消費税計算</title>
<style type="text/css">
h1 {
font-size: 18pt;
font-weight: bold;
color: gray;
}
body {
font-size: 13pt;
color: gray;
margin: 5px 25px;
}
</style>
<script th:inline="javascript">
function action() {
var val = document.getElementById("text1").value;
var res = parseInt(val * ((100 + /*[[${tax}]]*/) / 100));
document.getElementById("msg").innerHTML = "include tax: " + res;
}
</script>
</head>
<body>
<h1>JavaScriptのインライン処理で消費税計算</h1>
<p id="msg"></p>
<input type="text" id="text1" />
<button onclick="action()">click</button>
</body>
</html>
テンプレートフラグメント
part.html を作成する。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>part page</title>
<style th:fragment="frag_style">
div.fragment {
border:solid 3px lightgray;
padding: 0px 20px;
}
</style>
</head>
<body>
<h1>Part page</h1>
<div th:fragment="frag_body">
<h2>fragment</h2>
<div class="fragment">
<p>this is fragment content.</p>
<p>sample message..</p>
</div>
</div>
</body>
</html>
frag.html を作成する。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>top page</title>
<style th:include="part :: frag_style"></style>
</head>
<body>
<h1>Top page</h1>
<div th:include="part :: frag_body">
<p>this is original content.</p>
</div>
</body>
</html>
IndexController.java に frag() メソッドを追加する。
@RequestMapping("/frag")
public String frag() {
return "frag";
}
frag.html にヘッダーとフッターを別ファイルから読み込むようにしてみる。
<body>
<div th:include="part :: header">
<p>this is original content.</p>
</div>
<h1>Top page</h1>
<div th:include="part :: frag_body">
<p>this is original content.</p>
</div>
<p>ここが本文ですよ</p>
<div th:include="part :: footer">
<p>this is original content.</p>
</div>
</body>
part.html に共通で使うヘッダーとフッターを用意する。
<body>
<div th:fragment="header">
<p>ここがヘッダーです</p>
<hr />
</div>
<h1>Part page</h1>
<div th:fragment="frag_body">
<h2>fragment</h2>
<div class="fragment">
<p>this is fragment content.</p>
<p>sample message..</p>
</div>
</div>
<div th:fragment="footer">
<hr />
<p>ここがフッターです</p>
</div>
</body>
モデルとデータベース
次章のモデルとデータベースに進む準備として、pom.xml に新しい依存関係を追加する。
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>jp.abc</groupId> <artifactId>MyBootApp</artifactId> <version>0.0.1-SNAPSHOT</version> <name>MyBootApp</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>