1. 程式人生 > >springboot整合freemarker和thymeleaf

springboot整合freemarker和thymeleaf

整合freemarker

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-freemarker -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-freemarker</artifactId>
		</dependency>

application.properties中配置: 

############################################################
#
# freemarker 靜態資源配置
#
############################################################
#設定ftl檔案路徑
spring.freemarker.template-loader-path=classpath:/templates
# 關閉快取, 即時重新整理, 上線生產環境需要改為true
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.ftl

注意freemarker檔案字尾名是.ftl

在templates中新建資料夾freemarker,裡面存放index.ftl,完全就是html的格式

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Freemarker渲染頁面</title>
</head>
<body>
    hello ${user}
</body>
</html>
	@GetMapping("/free")
	public String showFreeMarker(ModelMap modelMap) {
		User user=new User();
		user.setName("cm123");
		user.setAge("23");
		user.setPassword("321654");
		user.setBirthday(new Date());
		modelMap.addAttribute("user",user);
		return "freemarker/index";
	}

整合thymeleaf

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
			<version>2.0.4.RELEASE</version>
		</dependency>
############################################################
#
# thymeleaf 靜態資源配置
#
############################################################
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
# 關閉快取, 即時重新整理, 上線生產環境需要改為true
spring.thymeleaf.cache=false

注意thymeleaf檔案字尾名是.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Thymeleaf</title>
</head>
<body>
<h1 th:text="${user}">hello thymeleaf</h1>
<span>ll</span>
</body>
</html>

 

thymeleaf有一些特殊的標籤後面介紹。。。