在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
相关代码可以调试abstractcachingviewresolver类,由图可知,如果spring.thymeleaf.cache设置为true,则默认缓存数量为1024个文件。
为false的话,则不缓存,每次都重新创建view,因此,每次加载(不管有没有修改)都是创建新的文件。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论