Controller
Thymeleaf については次のリンクを参照してください。
http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf_ja.html
Thymeleaf を Spring Boot で使えるようにするために、build.gradle の dependencies に次の行を追加します。
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
1. Index
PROJECT_ROOT/src/main/resources/templates/index.html を作成します。
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"/> <title th:text="#{title}">TITLE</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <p th:text="#{welcome}">WELCOME</p> </body> </html>
PROJECT_ROOT/src/main/resources/messages.properties を作成します。
title=title welcome=Welcome!!
コントローラを作成します。
package com.example; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class IndexController { @GetMapping("/") public String index() { return "index"; } }
コントローラのメソッドが返す文字列に .html を付加した templates ディレクトリにあるファイルを Thymeleaf のテンプレートとして使用して、HTML をブラウザに返します。
./gradlew bootRun
で起動して、ブラウザで http://localhost:8080 にアクセスした画面は下のようになります。
2. ロケール
デフォルトでは、org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver を使用して、ブラウザから送られる accept-language を使用したロケールでメッセージが表示されます。
org.springframework.web.servlet.i18n.CookieLocaleResolver, org.springframework.web.servlet.i18n.SessionLocaleResolver, org.springframework.web.servlet.i18n.FixedLocaleResolver を使用した、クッキー、セッション、固定といったあらかじめ用意された LocaleResolver を使用することもできます。
ここでは独自の LocaleResolver を作成して日本語(osaka_JP)になるようにしてみます。
package com.example; import org.springframework.web.servlet.LocaleResolver; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Locale; public class OsakaLocaleResolver implements LocaleResolver { @Override public Locale resolveLocale(HttpServletRequest request) { return new Locale("osaka", "JP"); } @Override public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) { throw new UnsupportedOperationException("unsupported"); } }
package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean OsakaLocaleResolver localeResolver() { return new OsakaLocaleResolver(); } }
PROJECT_ROOT/src/main/resources/messages_osaka.properties を作成します。
title=タイトル welcome=大阪にようこそ
実行して、http://localhost:8080 にアクセスしてみます。
./gradlew bootRun