Spring BootとThymeleafでWebアプリ制作
Spring Bootとは
JavaのフレームワークであるSpring FrameworkでWebアプリを簡単に作成できるように作られたフレームワーク
プロジェクト作成
- 依存性:
- 「Thymeleaf」を選択
- 「Spring Web」を選択(これを選択しないとmvcに必要な機能が使えない。RequestMappingとか)
コントローラとテンプレートの作成
以下2つのファイルを作成します。
package com.sample; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/sample") public class SampleController { @RequestMapping(method = RequestMethod.GET) public String test(Model model) { model.addAttribute("name", "草刈"); model.addAttribute("get", "GET /sample"); model.addAttribute("post", "POST /sample"); return "sample/index"; } }
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>top page</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <h2 th:text="${name}"></h2> <p th:text="${get}" /> <p th:text="${post}" /> </body> </html>
以下のURLにアクセスすると結果がブラウザに表示されます。 http://localhost:8080/sample