springboot + Thymeleaf页面模板标签生成静态页面

时值中秋,每逢佳节倍思亲;思乡之情怎一句每逢佳节倍思亲所能形容的,也许久没有写blog了,前段时间由于其他原因,状态一直不好,现在调整了一下,整理一下,把之前用到的东西记录一下。最近在搞一个博客系统,由于pv,uv比较高,各方面综合考虑,准备用静态页面思路来实现这个功能。

下面就详细介绍下:

spring页面模板引擎常用的有freemarker, jsp 以及 thymeleaf,其中thymeleaf 是springboot官方推荐引用的模板引擎;

本文也主要介绍springboot集成thymeleaf;

1 首先pom.xml文件引入(springboot-thymeleaf-start)

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

2 配置properties文件

#THYMELEAF (ThymeleafAutoConfiguration)  
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#开发环境关闭缓存   生产环境开启
spring.thymeleaf.cache=false

2 准备模板页面以及一些后台定义的页面变量 

${name}, ${array},${content}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 th:text="${name}">列表名称</h1>
<ul>
    <li th:each="item: ${array}" th:text="${item}">条目</li>
</ul>

<div th:utext="${content}"></div>

</body>
</html>

下面就是后台代码,填充页面变量内容,并保存为静态页面

 @Autowired
    private SpringTemplateEngine templateEngine;
    @GetMapping(value = "/testTemplate")
    @ResponseBody
    public void testTemplate() throws IOException {

        //构造上下文(Model)
        Context context = new Context();
        context.setVariable("name", "蔬菜列表");
        context.setVariable("array", new String[]{"土豆", "番茄", "白菜", "芹菜"});
        context.setVariable("content", "titl=test&typ=1&cont=<p><strong>tes&nbsp;</strong></p>\n" +
                "\n" +
                "<h1><strong>3333333333333</strong></h1>\n" +
                "\n" +
                "<p>&nbsp;</p>\n" +
                "\n" +
                "<p>11111111111111</p>\n" +
                "\n" +
                "<p>1</p>\n" +
                "\n" +
                "<p>3333333333333</p>\n" +
                "\n" +
                "<p>4444444444444<img alt=\"\" class=\"has\" height=\"189\" src=\"https://img-blog.csdnimg.cn/20190627172134852.png\" width=\"256\" />" +
                "77777777777777777777777</p>\n" +
                "&categories=小功能&chnl=28&level=0&tag2=&artid=93891432&private=true&stat=draft");
        //渲染模板可以保存到服务器本地目录下,也可以放在oss,七牛云上等等,
        FileWriter write = new FileWriter("E:\\result1.html");
        templateEngine.process("example", context, write);
    }

这样运行项目并访问这样本地目录下就产生了一个静态html页面

至此,springboot+thymeleaf 生成静态页面就结束了

发布了48 篇原创文章 · 获赞 7 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/maguoliang110/article/details/100773542