Thymeleaf模板引擎在Spring Boot中的使用
之前学习的引入资源没太弄懂,回过来看,到底什么是Thymeleaf?
1,什么是Thymeleaf?
(1) Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。
(2)类似JSP,Velocity,FreeMaker等, 它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。
(3)与其它模板引擎相比, Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。
2, 导入thymeleaf模块相关的starter
<!-- thymeleaf模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3,thymeleaf相关demo
已经导入了thymeleaf相关的starter,下面创建一个java:
package com.guigu.springboot.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@RequestMapping("/success")
public String success(ModelMap modelMap) {
String str = "hello, how are u?";
modelMap.addAttribute("hello", str);
return "success";
}
}
我们给ModelMap绑定一个属性上,属性名为hello,属性值为字符串:hello, how are u?
然后直接success字符串,thymeleaf就会自动加载calsspath:/templates/success.html
下面在templates文件夹下创建success.htm,
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>SUCCESS</title>
</head>
<body>
<div th:text="${hello}"></div>
</body>
</html>
导入thymeleaf的starter之后,穿件html时会在顶部自动加入thymeleaf的官网,这样我们在html里面写thymeleaf时会有语法提醒。
在div中加上了 th:text="${hello}", 这句的含义是,用这个值替换div的文本的值。
4,启动项目,然后访问success方法,就会输出我们在hello上绑定的值:hello, how are u?
thymeleaf使用起来,模式都一样,后台传值, html页面利用thymeleaf语法进行展示。
理解学习一点是一点,fighting!!!!!
学习资源:http://www.chilangedu.com/sectionq/1489582623/0FE7879F04947075