IT graph

気になったデバイスやプログラムで楽しくやっていけたら良いなと思っております。

Use Controller & Thymeleaf in Spring Boot2!

コンパイル環境はGradleです。まずは、build.propertyに以下のとおり、thymeleafを利用できるようにする。

dependencies {
    compile('org.springframework.boot:spring-boot-starter-thymeleaf')

 
次はController。 @Controllerアノテーションで通常のWebページに遷移できるようにし、ModelAndViewに[Webページで 利用するオブジェクト]と[Webページの名前]をセットし、戻り値で返す。

package com.hello;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller  
public class HelloController {
    @RequestMapping(path = "/hello", method = RequestMethod.GET)  // GETリクエストで"/hello"をしていされた場合にこのメソッドを呼ぶ
    public ModelAndView sample(ModelAndView mav) {            //戻り値はModelAndViewクラス
        mav.addObject("message", "Make java great again!!");  //ModelAndViewクラスにmessageオブジェクトを追加
        mav.setViewName("hello");                                             //ModelAndViewクラスにViewのページ名を指定
        return mav;                                                      //ModelAndViewを返す
    }
}

 
Webページ(hello.html)の設定は以下。th:textはThymeleafで利用するタグでmessageという変数を 表示する。

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8" />
        <title>Hello World!</title>
    </head>
    <body>
        <h1 th:text="${message}"></h1>
    </body>
</html>

実際にアクセスしてみると・・・ はいデター!!!

f:id:ice_black:20180422190252p:plain:w300