SpringBoot学习日志之_DAY04整合前端模板thymeleaf

 什么是thymeleaf

之前一直是采用的JSP作为前端模板,但是在springboot当中是推荐Thymeleaf当中前端模板的, Thymeleaf是一个跟 Velocity、FreeMarker 类似的模板引擎。

官方教程Tutorial: Using Thymeleaf

创建项目

首先引入springboot对Thymeleaf的依赖

		<!--界面模板引擎thymeleaf依赖 springboot推荐 代替JSP-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
复制代码

然后在application.properties当中添加相关配置信息

#thymeleaf 配置信息
#取消缓存,修改HTML界面后立即生效,不然会读取缓存,没有变化
spring.thymeleaf.cache=false
#下面5个配置信息都是常用的默认的配置信息,如果不需要修改,不写也行
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.servlet.content-type=text/html
复制代码

创建controller以及在/templates/下创建一个index.html的文件

@Controller
public class ThymeleafController {

    @GetMapping("/index")
    public String show(Model model){
        model.addAttribute("username", "hjljy");
        model.addAttribute("success", "成功显示相关信息");
        return "index";
    }

    @GetMapping("/index1")
    public String show1(Model model){
        return "index1";
    }

}
复制代码

index.html   添加 通过th进行取值

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>网站名称</title>
</head>
<body>
<p th:text="${username}"> </p>
<p th:text="${success}"> </p>
</body>
</html>
复制代码

index1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  success thymeleaf
</body>
</html>
复制代码

进行测试

分别输入:localhost:8080/index  localhost:8080/index1查看效果

参考文档:www.cnblogs.com/jiangbei/p/…

猜你喜欢

转载自juejin.im/post/7031057538904752141