テンプレートエンジンとデータベースの利用

テンプレートエンジンのThymeleafと、HSQLDBデータベースを使うために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 https://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.2.1.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</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>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</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>

入力フォームを使ってデータのやりとりを行う

form1.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>入力フォーム</title>
</head>
<body>

<h1>form1</h1>
<p th:text="${msg}"></p>
<form action="/form1" method="post">
	おなまえ:<input type="text" name="name" />
	<br />
	評価:<input type="text" name="eval" />
	<input type="submit" value="Click!" />
</form>

</body>
</html>

IndexController.java に form1 へのリクエストを処理するコードを追加する。

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class IndexConroller {
	@RequestMapping("/test")
	public ModelAndView index(ModelAndView model) {
		model.setViewName("index");
		model.addObject("msg", "サーバーで設定したメッセージですよ");
		return model;
	}

	@RequestMapping(value="/form1", method=RequestMethod.GET)
	public ModelAndView form(ModelAndView model) {
		model.setViewName("form1");
		return model;
	}

	@RequestMapping(value="/form1", method=RequestMethod.POST)
	public ModelAndView form1(ModelAndView model,
			@RequestParam("name") String name,
			@RequestParam("eval") String eval) {
		model.setViewName("form1");
		int percent = (name + eval).hashCode() % 101;
		percent = Math.abs(percent);
		String result = name + " さんの " + eval + " 度は" + percent + "%です。";
		model.addObject("msg", result);
		return model;
	}
}

th:each を使って複数の要素を表示する

コントローラにListを用意して過去の内容を保存できるようにする。
また、Listをテンプレートに渡すようにする。

package com.example.demo;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class IndexConroller {
	private List<String> list = new ArrayList<>();

	@RequestMapping("/test")
	public ModelAndView index(ModelAndView model) {
		model.setViewName("index");
		model.addObject("msg", "サーバーで設定したメッセージですよ");
		return model;
	}

	@RequestMapping(value="/form1", method=RequestMethod.GET)
	public ModelAndView form(ModelAndView model) {
		model.setViewName("form1");
		return model;
	}

	@RequestMapping(value="/form1", method=RequestMethod.POST)
	public ModelAndView form1(ModelAndView model,
			@RequestParam("name") String name,
			@RequestParam("eval") String eval) {
		model.setViewName("form1");
		int percent = (name + eval).hashCode() % 101;
		percent = Math.abs(percent);
		String result = name + " さんの " + eval + " 度は" + percent + "%です。";
		list.add(result);
		model.addObject("msg", result);
		model.addObject("list", list);
		return model;
	}
}

テンプレートに th:each を追加して複数の要素を表示する。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>入力フォーム</title>
</head>
<body>

<h1>form1</h1>
<p th:text="${msg}"></p>
<form action="/form1" method="post">
	おなまえ:<input type="text" name="name" />
	<br />
	評価:<input type="text" name="eval" />
	<input type="submit" value="Click!" />
</form>

<hr />

<table>
  <tr th:each="obj : ${list}">
    <td th:text="${obj}"></td>
  </tr>
</table>


</body>
</html>

診断を追加してみる

IndexControllerの追加

	@RequestMapping(value="/form2", method=RequestMethod.GET)
	public ModelAndView form2(ModelAndView model) {
		model.setViewName("form2");
		return model;
	}

	@RequestMapping(value="/form2", method=RequestMethod.POST)
	public ModelAndView result(ModelAndView model,
			@RequestParam("name") String name) {
		String[] s = {"優しさ", "冷たさ", "面白さ", "熱血さ", "冷静さ",
					  "真面目さ", "可愛さ", "素直さ", "明るさ", "責任感" };
		StringBuilder sb = new StringBuilder();
		sb.append(name).append(" さん。。。").append("<br />");
		for (String t : s) {
			int percent = (name + t).hashCode() % 101;
			percent = Math.abs(percent);
			sb.append(t).append(" ... ");
			sb.append(percent).append("%").append("<br />");
		}
		model.addObject("msg", sb.toString());
		model.setViewName("form2");
		return model;
	}

form2.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>入力フォーム</title>
</head>
<body>

<h1>form2</h1>
<form action="/form2" method="post">
	おなまえ:<input type="text" name="name" />
	<br />
	<input type="submit" value="診断" />
</form>

<hr />
<p th:utext="${msg}"></p>

</body>
</html>

Webアプリ開発(再チャレンジ)

メニューから[新規]-[プロジェクト]を選択する。

SpringBootの中にある「Springスタータープロジェクト」を選択する。
Webの中にある「Spring Web」を選択して「完了」する。

プロジェクト名「demo」を右クリックして[Maven]-[プロジェクトの更新]を選択する。
「OK」をクリックすると画面下のステータスバーに何か処理が動いている表示になる。

プロジェクトの更新が終わったらプロジェクト名「demo」を右クリックして[実行]-[maven install]を選択する。
コンソールにいろいろと表示され、最後のほうに「BUILD SUCCESS」と表示されればOK!

なぜか、SpringBootアプリケーションとして起動しても動作しないので、設定を変更して、別に準備したTomcat上で動作させてみる。

demo プロジェクトを右クリックして「プロパティ」を選択し、左側から「プロジェクト・ファセット」を選択する。

以下の図のように、チェックした状態で「適用して閉じる」をクリックする。

demo を右クリックして「実行」‐「SpringBootアプリケーション」を選択するとWebアプリケーションが起動する。

コンソールに「 Started DemoApplication in 2.426 seconds (JVM running for 2.933)」のような表示が出ていればOK。

画面上に「プロジェクト・エクスプローラー」が表示されていない場合は、メニューバーから「ウィンドウ」‐「パースペクティブ」‐「パースペクティブを開く」‐「その他」を選択する。

パースペクティブの一覧が表示されるので、「JavaEE」を選択して「開く」をクリックする。

コントローラの作成

コントローラクラスを作成する。

プロジェクト・エクスプローラーで「Javaリソース」‐「src/main/java」-「com.example.demo」を右クリックし「新規」‐「クラス」を選択する。

名前に「HelloController」と入力し「完了」をクリック。

http://localhost:8080/hello にアクセスすると、画面上に「Hello World!」と表示される。

静的HTMLファイルの表示

src/main/resource を右クリックして「新規」‐「フォルダ」を選択する。
「public」フォルダを作成する。

public を右クリックし「新規」‐「その他」を選択する。
「HTMLファイル」を選択して index.html を作成する。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello index.html</title>
</head>
<style>
h1 {
  color: red;
}
div.border {
	border: solid 2px blue;
	border-radius: 5px;
	padding: 5px;
}
</style>
<body>


<h1>Hello</h1>
<p>Hello index.html</p>

<div class="border">
div タグにボーダーを追加する例
</div>

<hr />

<p>src/main/resources/public/index.html</p>

</body>
</html>

http://localhost:8080/ にアクセスすると、public/index.html の内容が表示される。

コントローラとビューの利用

今回はライブラリの不足のために動作しないが、SpringBootの場合、ControllerとViewを組み合わせてWebサイトを作成する。

src/main/java の com.example.demo を右クリックし「新規」‐「クラス」を選択する。

/test というURLにアクセスが来たら、templates/index.html を表示する仕組みを作成する。

IndexController.java

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexConroller {
	@RequestMapping("/test")
	public String index() {
		return "index";
	}
}

src/main/resources の temlates を右クリックし「新規」‐「その他」を選択する。
「HTMLファイル」を選択し、 index.html を作成する。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Controller test</title>
</head>
<body>
Hello src/main/resources/templates/index.html
</body>
</html>

サーバーにデータを問い合わせる

Beer クラスを作成する。

Beer.java

package com.example.demo;

public class Beer {
	private String name;
	private int price;
	public Beer(String name, int price) {
		this.name = name;
		this.price = price;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}

}

ビールのリストを返すコントローラを作成する。

package com.example.demo;

import java.util.ArrayList;
import java.util.List;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class BeerController {
	@RequestMapping("/beer")
	public List<Beer> beers() {
		List<Beer> list = new ArrayList<>();
		list.add(new Beer("一番搾り", 200));
		list.add(new Beer("プレミアムモルツ", 240));
		list.add(new Beer("ギネス", 300));
		return list;
	}
}

ブラウザでJSONデータを受け取れるようになったので、AJAXを使ってデータを受信し、画面を更新するようにしてみる。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello index.html</title>
<script src="jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$.ajax({
	url: '/beer',
	dataType: 'json',
	success: function(data) {
		result(data);
	}
});

function result(data) {
	var div = $('#beers');
	$.each(data, function(i) {
		console.log(data[i]);
		var beer = $('<div>');
		var name = $('<span>').text(data[i].name);
		var price = $('<span>').text(data[i].price + '円');
		beer.append(name);
		beer.append(price);
		div.append(beer);
	});
}
</script>
</head>
<style>
h1 {
  color: red;
}
div.border {
	border: solid 2px blue;
	border-radius: 5px;
	padding: 5px;
}
</style>
<body>


<h1>Hello</h1>
<p>Hello index.html</p>

<div class="border">
div タグにボーダーを追加する例
</div>

<div id="beers"></div>

<hr />

<p>src/main/resources/public/index.html</p>

</body>
</html>