この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
はじめに
Thymeleafを使うとWebページとの結びつけるのが簡単にできるという事で使ってみました。
環境
Mac OSX 10.10.5 Yosemite Eclipse 4.5.1 Spring Boot 1.3.5
ブラウザに表示する
準備
dependencies {
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
compile('org.springframework.boot:spring-boot-starter-web')
runtime('org.postgresql:postgresql')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
基本的な設定は前回の記事などをご覧いただきたいのですが、 build.gradleのdependenciesにThymeleafを追加します。 GradleをRefreshして必要な物をダウンロードする事で準備が整います。
コード
ウェブページ:test.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Thymeleaf</title>
</head>
<body>
<h1>Thymeleaf</h1>
<dl>
<dt>id</dt>
<dd th:text="${db.id}"></dd>
<dt>title</dt>
<dd th:text="${db.title}"></dd>
<dt>count</dt>
<dd th:text="${db.count}"></dd>
</dl>
</body>
</html>
ウェブページを作ります。 src/main/resourcesのtemplatesの中にhtmlファイルを配置してください。 表示内容は、最上段に"Thymeleaf"、その下にid、title、countと順に表示するだけです。
Counter.java
package com.blog;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
public class Counter {
@Id
@Column(name="id")
public Integer id;
@Column(name="title")
private String title;
@Column(name="count")
private int count;
// getter, setter
public Integer getID() {return id;}
public void setId(Integer no) {this.id = no;}
public String getTitle() {return title;}
public void setTitle(String title) {this.title = title;}
public int getCount() {return count;}
public void setCount(int count) {this.count = count;}
}
画面に表示させるためのパーツを定義します。
コントローラー:WebController
package com.blog;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/test")
public class WebController {
@RequestMapping(method=RequestMethod.GET)
public String test(Model model) {
Counter cntr = new Counter();
cntr.setId(1);
cntr.setTitle("title");
cntr.setCount(0);
model.addAttribute("db", cntr);
return "test";
}
}
9行目:@RequestMappingで「/test」と接続するurlを作成。 12行目:「/test」でこのメソッドに繋がるように設定。 14〜17行目:表示させる値をセット。 18行目:セットした値の一群を表示させるための設定。 20行目:「test」で、「test.html」を指定。
ブラウザで表示
実行し、「http://localhost:8080/test」に接続すると、下の画面が表示されると思います。
カウンター機能を追加する
今のままだと同じ文字しか表示されないので、 「http://localhost:8080/test」に接続する度にカウンターが増えていく様にします。
準備
テーブル
CREATE DATABASE sbdb;
CREATE TABLE counter (
id SERIAL PRIMARY KEY
, title VARCHAR(10) NOT NULL
, count INT NOT NULL);
INSERT INTO counter VALUES (1,'select',0);
sbdb=# select * from counter;
id | title | count
----+--------+-------
1 | select | 0
(1 rows)
DB接続設定:application.yml
spring:
datasource:
url: jdbc:postgresql://localhost/sbdb
username: XXXX
password: YYYY
driverClassName: org.postgresql.Driver
データベースの接続設定を行います。 src/main/resources傘下にフォルダ「config」を作って入れます。 下記はPostgreSQLの設定です。
コード
Counter.java
画面に表示させるためのパーツを定義します。
package com.blog;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="counter")
public class Counter {
@Id
@Column(name="id")
public Integer id;
@Column(name="title")
private String title;
@Column(name="count")
private int count;
// getter, setter
public Integer getID() {return id;}
public void setId(Integer no) {this.id = no;}
public String getTitle() {return title;}
public void setTitle(String title) {this.title = title;}
public int getCount() {return count;}
public void setCount(int count) {this.count = count;}
}
一行追加しました。 11行目:@Tableでテーブル「counter」を指定。
リポジトリ:CounterRepository
package com.blog;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CounterRepository extends JpaRepository<Counter, Integer> {
}
前回の記事と同じく、JpaRepositoryを継承するだけです。
サービス:CounterService
package com.blog;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class CounterService {
@Autowired
CounterRepository repository;
public Counter select(Integer id) {
return repository.findOne(id);
}
public Counter save(Counter counter) {
return repository.save(counter);
}
}
14〜15行目:リポジトリを繋げます。 17〜19行目:IDで指定したレコードをDBから取得するメソッド。 21〜23行目:DBに値を保存するメソッド。
コントローラー:WebController
package com.blog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/test")
public class WebController {
@Autowired
CounterService service;
@RequestMapping(value="/1", method=RequestMethod.GET)
public String test2(Model model) {
int cnt = service.select(1).getCount();
String title = service.select(1).getTitle();
Counter counter = new Counter();
counter.setId(1);
counter.setTitle(title);
counter.setCount(cnt+1); // +1でカウンターを増やす
model.addAttribute("db", counter);
service.save(counter);
return "test";
}
}
13〜14行目:サービスを@Autowiredで繋げます。 16行目:@RequestMappingで「value="/1"」を設定したので、urlに"/1"を追加すればこのメソッドに繋がります。 18〜19行目:DBの値を取得し、 21〜24行目:その値をセットしつつ、カウンターを増やします。 26行目:「test.html」に表示させる値の一群をセット。 28行目:カウンターを増やしたので、その値をDBに保存。 30行目:「test.html」を指定。
ブラウザで表示
実行し、「http://localhost:8080/test/1」に接続します。 ブラウザでリロードする度に「count」の数値が1づつ増えていくのが確認できました。
さいごに
どうでしょうか。 アノテーションがだいぶ増えてきましたので最初は戸惑いましたが。 それぞれの関係性を細かく見れば、これ位なら難しいものではないと感じました。