SpringBoot入门系列篇(五):简单使用thymleaf模板

前情提要

使用过vue.js的人都知道它的数据绑定是多么的方便,其实通过纯js,我们也可以实现这种操作,通过Ajax异步获取数据并放入相应的元素中,而在SpringBoot中,也同样提供了数据绑定的实现,通过使用thymleaf模板,可以实现类似于vue.js那样的数据绑定,只需要访问一个url,就能动态获取里面的所有数据


SpringBoot使用thymleaf模板的简单实例

首先,我们需要引入thymleaf模板的依赖,SpringBoot默认使用的就是thymleaf,所以我们在pom.xml中引入如下:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
然后创建一个Controller类,这里需要注意的是:Controller类的修饰注解不是@RestController,而是@Controller,他们的区别可以去百度:
package org.framework.demo.section1;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

/**
 * 使用模板
 * @author chengxi
 */
@Controller
public class TemplateController {

    @RequestMapping("/temp")
    public String gettemp(Map<String,String> map){

        map.put("info","hello thymeleaf");
        return "/temp1";
    }
}
接下来就需要创建模板文件了,上面的请求对应的模板文件就是classpath: templates/temp1.html,默认是html文件,然后我们在resources目录下面创建templates文件夹,该文件夹是SprignBoot模板文件默认的目录,在该目录下面创建temp1.html,如果想要使用请求处理方法中map注入的info可以在temp1.html文件中写入如下代码:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <title>Hello HTML</title>
</head>
<body>
    <h1 th:text="${info}"></h1>
</body>
</html>
在html中thymleaf模板的使用类似于vue.js
接下来,启动tomcat测试类,输入网址:localhost:8080/temp就会看到输出的页面是我们编写的temp1.html文件


初使用thymleaf的404错误:meta

这里需要注意的是,使用thymleaf模板时,创建的html文件是在classpath:templates目录下的,而且SpringBoot中使用的是Thymleaf2.0版本的,所以所解析的不是基于html的,而是基于xml的,因此<meta ...>这类的标签会报错404,有两种方式,改成<meta ... />或者修改SpringBoot默认的thymleaf模板版本为3.0,具体的可以参考优秀博客: springboot中使用thymeleaf模板

thymleaf模板文件中引入外部文件

在thymleaf模板中引入外部的js/css/img文件时,对应的文件是放在classpath: static目录下面的,因此我们使用外部的js、css、img文件时需要创建与templates同级的static并放到这里面,目录使用的方式为:/js/index.js格式,具体可以参考优秀博客:springBoot项目中使用了thymeleaf模板,怎么在html文件中调用外部的.js文件

thymleaf模板文件的实时编辑

在使用thymleaf模板的时候,我们会发现一个问题,就是我们引入了html文件之后,在不重启项目的情况下改变html文件,然后保存,刷新页面,效果仍然没变,这是因为thmyleaf的缓存导致的,要想实时改变,就需要关闭thymleaf的缓存,关闭的方式很简单,在application.properties属性配置文件中添加如下一行代码:
spring.thymleaf.cache = false
这样一来,就能关闭thymleaf的缓存,从而实现实时编辑html文件了
发布了207 篇原创文章 · 获赞 75 · 访问量 36万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章