SpringBoot+Thymeleaf入門
SpringBootとThymeleafをさわってみた。
「SpringBootSample」というプロジェクトをGradleベースで作る。
■環境
> gradle -v ------------------------------------------------------------ Gradle 2.3 ------------------------------------------------------------ Build time: 2015-02-16 05:09:33 UTC Build number: none Revision: 586be72bf6e3df1ee7676d1f2a3afd9157341274 Groovy: 2.3.9 Ant: Apache Ant(TM) version 1.9.3 compiled on December 23 2013 JVM: 1.7.0_71 (Oracle Corporation 24.71-b01) OS: Windows 7 6.1 amd64
プロジェクトを作成する。
> mkdir SpringBootSample > cd SpringBootSample > gradle init --type java-library
「build.gradle」を編集する。
■build.gradle
buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.2.RELEASE") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'idea' apply plugin: 'spring-boot' [compileJava, compileTestJava]*.options*.encoding = 'UTF-8' jar { baseName = 'SpringBootSample' } repositories { mavenCentral() } sourceCompatibility = 1.7 targetCompatibility = 1.7 dependencies { compile("org.springframework.boot:spring-boot-starter-thymeleaf") compile("org.hibernate:hibernate-validator") compile("org.apache.tomcat.embed:tomcat-embed-el") testCompile("junit:junit") } task wrapper(type: Wrapper) { gradleVersion = '2.3' }
「resources」ディレクトリを作成して、デフォルトで作成されるクラスを消して、Eclipseプロジェクト化する。
> gradle eclipse
以下、作成物と概要。
- jp.sample.Application
- アプリ起動クラス
- @SpringBootApplicationアノテーションを使うのがポイント
- jp.sample.model.Person
- フォームに使うクラス
- BeanValidationする
- 「name」は1以上100以下の文字列長、「age」はnullでない且0以上の数字であることをチェックする
- jp.sample.controller.SampleController
- コントローラクラス
- resources/templates/index.html
- Thymeleafで作ったTOPページ
- templates配下に置く
- resources/templates/hello.html
- Thymeleafで作った挨拶ページ
■jp.sample.Application
package jp.sample; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
■jp.sample.model.Person
package jp.sample.model; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class Person { @Size(min=1, max=100) private String name; @NotNull @Min(0) private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
■jp.sample.controller.SampleController
package jp.sample.controller; import javax.validation.Valid; import jp.sample.model.Person; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class SampleController { @ModelAttribute private Person setUpPersonForm() { return new Person(); } @RequestMapping(value="/", method=RequestMethod.GET) public String index() { return "index"; } @RequestMapping(value="/hello", method=RequestMethod.POST) public String hello(@Valid Person person, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return "index"; } return "hello"; } }
「@ModelAttribute」で各メソッドで「model.addAttribute(new person());」を省略できる。
■resources/templates/index.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Top</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> はじめまして。あなたのことを教えてください。 <form th:action="@{/hello}" th:object="${person}" method="post"> <table> <tr> <td>Name:</td> <td><input type="text" th:field="*{name}" /></td> <td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</td> </tr> <tr> <td>Age:</td> <td><input type="text" th:field="*{age}" /></td> <td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">Name Error</td> </tr> <tr> <td><button type="submit">Submit</button></td> </tr> </table> </form> </body> </html>
■resources/templates/hello.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Hello !</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <p th:text=" ${person.name} + 'さん、こんにちは!'" /> <p th:text=" ${person.age} + '歳なんですね!'" /> </body> </html>
ブラウザで「http://[FQDN]:8080/」へアクセスすると名前と年齢を聞かれるので応えると挨拶してくれる。
参考:
http://spring.io/guides/gs/validating-form-input/
http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/
http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf_ja.html