Spring BootでThymeleafを使う
Spring BootはSpringや依存するライブラリをまとめて、Springでの開発をしやすくするもののようです。
あとサーブレットコンテナが組み込まれていたり、コマンドラインから稼働中のWebアプリケーションにアクセスできる仕組みが提供されているようです。
GradleでGetting Startedをやってみましたがいいかんじです。
依存するライブラリをちまちま書かなくてよかったり、コマンドライン一行で起動できたりして便利です。
Getting StartedではRestControllerでhtmlのViewを使っていないので、今回はViewを使ってみます。
Viewはjspやいくつかのテンプレートエンジンを選べるようですが、Thymeleafがいちおしっぽいので、これを使ってみます。
Gradleの設定
まずはbuild.gradleにthymeleafのライブラリを追加します。
gradle
dependencies {
// tag::jetty[]
compile("org.springframework.boot:spring-boot-starter-web") {
exclude module: "spring-boot-starter-tomcat"
}
compile("org.springframework.boot:spring-boot-starter-jetty")
// end::jetty[]
// tag::actuator[]
compile("org.springframework.boot:spring-boot-starter-actuator")
// end::actuator[]
// 追加
compile("org.thymeleaf:thymeleaf-spring4");
testCompile("junit:junit")
}
Controllerの作成
RestControllerではなく普通のControllerにします。
index()のreturnでテンプレート名を返します。
java
// src/main/java/com/misfrog/blog/IndexController.java
@Controller
@EnableAutoConfiguration
public class IndexController {
@RequestMapping( "/")
public String index() {
return "index/index";
}
}
テンプレート
テンプレートはデフォルトでsrc/main/java/templatesに置くようです。
“index/index”としたのでindexディレクトリを切ってその下にindex.htmlを作ります。
html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Hello Thymeleaf!</h1>
</body>
</html>
実行
$ ./gradlew build && java -jar build/libs/spring-simple-blog-0.1.0.jar
いけましたね!
※ Githubにソースを置いています。