java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > spring-boot-starter-thymeleaf加载外部html文件

spring-boot-starter-thymeleaf加载外部html文件方式

作者:jforgame

本文介绍了在SpringMVC中使用Thymeleaf模板引擎加载外部HTML文件的方法,以及在Spring Boot中使用Thymeleaf的基本步骤,包括引入依赖、创建Controller、创建HTML文件、参数化访问、热加载和热更新文件

在Spring MVC中,我们可以使用Thymeleaf模板引擎来实现加载外部HTML文件。

1.Thymeleaf介绍

Thymeleaf是一种现代化的服务器端Java模板引擎,用于构建漂亮、可维护且易于测试的动态Web应用程序。它适用于与Spring框架集成,并且可以与Spring MVC或Spring Boot等框架一起使用。

Thymeleaf模板引擎允许开发人员在HTML页面中使用模板表达式,这些表达式可以动态地替换页面中的内容。它提供了丰富的表达式语法,可以从后端Java代码中获取动态数据,并在模板中进行显示。

与其他模板引擎相比,Thymeleaf具有以下特点:

2.springboot使用thymeleaf

使用spring-boot-starter-thymeleaf可以非常方便地使用thymeleaf,下面来看详细的例子。

2.1.引入spring-boot-starter-thymeleaf依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2.2.创建controller

@Controller
public class H5Controller {

    @GetMapping("/external")
    public String loadExternalHtml() {
        return "index";
    }
}
 

在上述示例中,index()方法处理根路径的GET请求,并返回"index"字符串。这意味着它将返回名为index.html的Thymeleaf模板。

现在,创建一个名为index.html的Thymeleaf模板,放置在src/main/resources/templates目录下(默认的Thymeleaf模板目录)

如果想重新定义模板目录路径,只需要修改application.properties文件

spring.thymeleaf.prefix=file:/F:/projects/eb/resources/html5/

2.3.创建简易html文件

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Index Page</title>
</head>
<body>
    <h1>This is the index page</h1>
</body>
</html>

2.4.浏览器访问

在浏览器输入localhost:8080/index.html,即可看到html内容。

2.5.参数化访问html文件

假设Thymeleaf目录下有很多文件,我们希望客户端能通过参数来选择加载某个文件,那么我们可以修改controller的代码。

@Controller
public class H5Controller {

    @GetMapping("/external")
    public String loadExternalHtml(@RequestParam String resource) {
        return resource; 
    }

}

浏览器重新输入(可以根据需要访问特定文件):

http://localhost:8080/external?resource=hello

2.6热加载文件

web项目有一个特殊要求,就是希望程序在运行器可以动态加载html文件。使用thymeleaf,我们可以自动实现。

在程序运行期间,我们往/templates目录下新增文件,在浏览器输入地址,即可访问新增的文件。

2.7热更新文件

如果已经添加的html文件,需要在程序运行期间修改内容呢?thymeleaf同样也支持。只需修改application.properties文件

spring.thymeleaf.cache=false

相关代码可以调试AbstractCachingViewResolver类,由图可知,如果spring.thymeleaf.cache设置为true,则默认缓存数量为1024个文件。

为false的话,则不缓存,每次都重新创建View,因此,每次加载(不管有没有修改)都是创建新的文件。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文