Home | 簡體中文 | 繁體中文 | 雜文 | 知乎專欄 | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 視頻教程 | 打賞(Donations) | About
知乎專欄多維度架構 | 微信號 netkiller-ebook | QQ群:128659835 請註明“讀者”

5.10. Spring boot with Thymeleaf

5.10.1. Maven

			
	<dependency>  
		<groupId>org.springframework.boot</groupId>  
		<artifactId>spring-boot-starter-thymeleaf</artifactId>  
	</dependency>
			
		

5.10.2. application.properties

創建目錄 src/main/resources/templates/ 用戶存放模板檔案

			
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false	
			
		

5.10.3. Controller

			
package cn.netkiller.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/")
public class HelloController {

	@GetMapping("/hello")
	// 如果此處使用 @ResponseBody,將會返回 "hello" 字元串,而不是模板
	public String test() {
		return "hello";

	}

	@RequestMapping("/hello1")
	public String hello1(Map<String, Object> map) {
		// 傳遞參數測試
		map.put("name", "Neo");
		return "thymeleaf";
	}

	@RequestMapping("/hello2")
	public ModelAndView hello2() {
		ModelAndView mv = new ModelAndView();
		mv.addObject("name", "Amy");
		mv.setViewName("thymeleaf");
		return mv;
	}

	@RequestMapping(value = "/{name}", method = RequestMethod.GET)
	public String getMovie(@PathVariable String name, ModelMap model) {
		model.addAttribute("name", name);
		return "hello";
	}

}			

			
		

5.10.4. HTML5 Template

在 src/main/resources/templates/ 目錄下創建模板檔案 hello.html

			
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Spring MVC + Thymeleaf Example</title>
</head>
<body>
	<h1>Welcome to Thymeleaf</h1>
	<span th:text="${name}"></span>
</body>
</html>