Google App Engine Java Standard環境に Spring Bootのテンプレートエンジン Thymeleafを適用

Google App Engine Java Standard 環境で手っ取り早くSpring Boot アプリケーションを開発する

の構成を成長させて、必要な道具をそろえていく。

この書籍によると、テンプレートエンジンとしては、Thymelear(タイムリーフ)がおすすめとのこと。この書籍にもあるように、「JSPでいいんじゃないの?」とも思ったが、ここは素直に従う。

利用するには、pom.xmlに以下を追記。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  4. </dependency>

1.テンプレートHTMLの配置

src/main/resources/templates 配下に、テンプレート index.html を配置

gae_spring_template_engine01

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Insert title here</title>
  6. </head>
  7. <body>
  8. ID:<p class="msg" th:text="${id}"></p>
  9. </body>
  10. </html>

2.コントローラー

コントローラーを記述

前回は、@RestController としたが、テンプレートエンジンを利用する場合、@Controller を利用するようだ。

とりあえず、アプリケーションからコントローラーを分離し、以下のような構成にしてみる。

api  : RestController

page : Controller

gae_spring_template_engine05

2.1 Page用コントローラー

HTMLページ用のコントローラー

  • パスパラメータのマッピング
  • テンプレート名を文字列で返す。
  • パラメータに、ModelAndViewを利用することもできる

など。

  1. package info.typea.page;
  2.  
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.ui.Model;
  5. import org.springframework.web.bind.annotation.PathVariable;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7.  
  8. @Controller
  9. public class PageController {
  10. @RequestMapping("/page/{id}")
  11. public String pageSample(
  12. @PathVariable String id,
  13. Model model) {
  14. model.addAttribute("id", id);
  15. return "index";
  16. }
  17. }

2.2.Api用コントローラー

最終的には、JavaScriptから、REST APIを呼び出す構成にすると思うので、分割動作確認。

  1. package info.typea.api;
  2.  
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5.  
  6. @RestController
  7. public class ApiController {
  8. @GetMapping("/api/hello")
  9. public String hello() {
  10. return "Hello GAE Java std env with Spring boot !";
  11. }
  12. }

3.動作確認

ローカルで動かす。OK

gae_spring_template_engine02

GAEにデプロイし、動作確認OK!

gae_spring_template_engine03

API側も確認OK

gae_spring_template_engine04

Follow me!

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です