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

1.Thymeleaf介绍

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

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

  • 自然的模板语法:Thymeleaf的模板语法非常类似于HTML,易于理解和编写。
  • 静态预览:在开发过程中,可以直接在浏览器中预览Thymeleaf模板,无需启动整个应用程序。
  • 强大的功能:Thymeleaf提供了丰富的标签和表达式,可以处理循环、条件判断、国际化等常见的模板需求。
  • 安全:Thymeleaf会对输出的内容进行自动转义,以防止XSS攻击。

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

不管有没有修改)都是创建新的文件。

springboot 动态加载rabbitmq springboot 动态加载外部jar_html