前言
本章讲解SpringBoot整合Thymeleaf的相关知识
方法
1.概念
通过前面的讲解,SpringBoot支持了JSP、FreeMarker等视图层技术。但是,SpringBoot推荐的视图层技术却是Thymeleaf。
所以,我们将重点讲解Thymeleaf的使用!
2.整合Thymeleaf步骤
1)在pom.xml中添加Thymeleaf启动器
<!-- 配置Thymeleaf启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2)编写controller
package cn.edu.ccut.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/showMsg")
public String getMsg(Model model){
model.addAttribute("msg", "this is thymeleaf !");
return "index";
}
}
3)配置Thymeleaf模板文件
这里只是简单的带大家了解一下该模板文件,实际上Thymeleaf通过其特定的语法对html做渲染。
如果要做到这一步,势必要知道Thymeleaf的相关语法,语法将会在后面的章节中进行体现!
本示例仅仅将controller中的msg值进行展示:
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Thymeleaf</title>
</head>
<body>
<span th:text="${msg}"></span>
</body>
</html>
4)配置启动器
package cn.edu.ccut;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
5)启动项目,输入http://localhost:8080/showMsg观察效果如下:
至此,一个简单的整合Thymeleaf的功能就写好了!