Spring Bootで画面遷移型アプリケーションを作成する
Spring Bootを使えば画面遷移型のアプリケーションも簡単に作ることができます。
テンプレートエンジンとして、次のライブラリがサポートされています。
- Thymeleaf
- FreeMarker
- Groovy templates
- Velocity
- Mustache
JSPの利用はさまざまな制約があるため、推奨されていないようです。
Spring Bootで画面遷移型アプリケーション
pom.xmlに以下の依存モジュールを追加します。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
次に、src/main/java
に以下のクラスを配置します。
RestaurantController.java
package com.example; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import con.example.tw.RestaurantBean; @Controller public class RestaurantController { final List<RestaurantBean> restaurantList = new ArrayList<RestaurantBean>(); public List<RestaurantBean> getRestaurants() { RestaurantBean bean = new RestaurantBean(); bean.setTagName("sampleTag"); bean.setTabelogUrl("https://www.google.com"); bean.setUserName("takashi"); bean.setTweet("this is nice restaurant!"); restaurantList.add(bean); return restaurantList; } @RequestMapping("/info") public String info(Model model) { model.addAttribute("title", "おいしいレストラン情報"); model.addAttribute("info", "This is Restaurant Infomation"); return "info"; } }
TemplateResolverがビュー名につけるプレフィックスとサフィックスのデフォルト値はそれぞれ"classpath:/templates/"と".html"になるため、 /src/main/resources/templates/info.htmlを配置します。
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8" /> <title th:text="${title}"></title> </head> <body> <p> <span th:text="${info}">Hello!</span> </p> </body> </html>
これで、localhost:8080/info にアクセスすると、
「This is Restaurant Infomation」
と表示されます。