似非プログラマのうんちく

「似非プログラマの覚え書き」出張版

春だから Spring やろうぜ(その 4)

まずは簡素なものを作ってみる

まずはフォームも何もない、ただページを表示させるだけのものを作ってみる。ただしメッセージはコントローラーから渡すようにする。

package jp.mydns.akanekodou.demo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {
    @RequestMapping("/")
    public String index(Model model) {
    	model.addAttribute("title", "Hello page");
    	model.addAttribute("message", "This is a message prepared by controller.");
    	return "hello";
    }
}

src/main/resources に既に templates フォルダが出来ているので、そこに hello.html を作る。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <title th:text="${title}"/>
    <link th:href="@{/css/hello.css}" rel="stylesheet" />
  </head>
  <body>
    <h1 th:text="${title}"/>
    <p th:text="${message}"/>
  </body>
</html>

CSS などの静的ファイルは src/main/resources/static 以下に配置して、そこからの相対パスで指定すれば良いが、上記のように th:href 属性に @{...} の形で指定する。

ちなみに CSS はこんな感じ。参考書からまるっと写した。

body {
  padding: 10px;
  color: #666;
}

実行するのは簡単で、「Run As」から「Spring Boot App」で良い。

f:id:redcat_prog:20180404184542p:plain

うむ、CSS もちゃんと反映されてる。