[SpringBoot2.4.3] thymeleafを使う

controller

package com.example.demo;

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

@Controller
public class HelloController {
	
	@RequestMapping("/")
	public String index() {
		return "index";
	}	
}

html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<style>
		h1 {
			font-size:18px;
			font-weight:bold;
			color:gray;
		}
		body {
			font-size:13px;
			color:gray;
			margin:5px 25px;
		}
	</style>
</head>
<body>
	<h1>Helo page</h1>
	<p class="msg">This is Thymeleaf sample page.</p>
</body>
</html>

<p class="msg" th:text="${msg}">This is Thymeleaf sample page.</p>
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Controller
public class HelloController {
	
	@RequestMapping("/{num}")
	public String index(@PathVariable int num, Model model) {
		int res = 0;
		for(int i = 1; i <= num; i++)
			res += i;
		model.addAttribute("msg", "total: "+ res);
		return "index";
	}	
}

ModelはWebページで利用するデータを管理するためのクラス

### formを使う

<body>
	<h1>Helo page</h1>
	<p class="msg" th:text="${msg}">Please wait...</p>
	<form method="post" action="/">
		<input type="text" name="text1" th:value="${value}">
		<input type="submit" value="click">
	</form>
</body>
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {
	
	@RequestMapping(value="/", method=RequestMethod.GET)
	public ModelAndView index(ModelAndView mav) {
		mav.setViewName("index");
		mav.addObject("msg", "お名前を書いて送信してください。");
		return mav;
	}
	
	@RequestMapping(value="/", method=RequestMethod.POST)
	public ModelAndView send(@RequestParam("text1")String str, ModelAndView mav) {
		mav.addObject("msg", "こんにちは、" + str + "さん!");
		mav.addObject("value", str);
		mav.setViewName("index");
		return mav;
	}
}

なるほどー