Springboot+Thymeleaf实现纯静态化页面处理

发布于:2024-08-01 ⋅ 阅读:(150) ⋅ 点赞:(0)

前言:引入包什么的就不讲了,这里我只记录如何实现。

  1. 在template目录下构建模板页面 IndexTemplate.html。一般模板文件都是放在这个下面
    <!DOCTYPE html>
    <html lang="zh" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Index静态页面模板</title>
        <link rel="stylesheet" th:href="@{css/bootstrap.min.css}" />
    </head>
    <body>
    <div>
        <p th:each="item:${article.list}">
            <span th:text="${item.title}"></span>
        </p>
    </div>
    </body>
    </html>
    
    注: 这里的css不起作用,只是标注下怎么使用
  2. 编写生成代码:
    @GetMapping("/generateIndexPage")
    @ResponseBody
    public void generateIndexPage(){
        String cacheStaticPagePath = "Z://";
        //String cacheStaticPagePath = "/home/tio2/fileCache";
        Map<String,Object> map = new HashMap<>();
        map.put("article", articleService.selectArticlePage(1,5,null,null));
        //创建thymeleaf上下文对像
        Context context = new Context();
        // 将Map对象mmp中的键值对设置为上下文变量, 这允许在模板渲染过程中访问这些变量
        context.setVariables(map);
    
        // 使用模板引擎处理前端首页模板,生成HTML内容:(模板名,上下文对象)
        String htmlContent = templateEngine.process("IndexTemplate", context);
        try{
            // 将HTML内容保存到指定的目录
            File file = new File(cacheStaticPagePath+"/index.html");
            //判断file文件是否存在
            if (file.exists()) {
                //存在就获取点年月日时分秒备份文件
                String date = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date());
                File bakFile = new File(cacheStaticPagePath+"/index_"+date+"_bak.html");
                // 将原文件重命名为备份文件
                file.renameTo(bakFile);
            }
            // 将生成的HTML内容写入到index.html文件
            FileCopyUtils.copy(htmlContent.getBytes(), file);
        } catch (IOException e){
            e.printStackTrace();
        }
    }
    
  3. 先前往Z盘中看看该文件是否生成,然后打开看看是否正常。这里不做展示了。
  4. 编写访问静态页面的代码:
    @GetMapping({"/showGeneratePage"})
    public void showGeneratePage(HttpServletResponse response){
        //读取本地Z://index.html文件
        File file = new File("Z://index.html");
        try {
            // 读取文件内容
            byte[] fileContent = FileCopyUtils.copyToByteArray(file);
            // 设置响应的Content-Type和字符编码
            response.setContentType("text/html;charset=UTF-8");
            // 将文件内容写入响应
            response.getWriter().write(new String(fileContent));
        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
        }
    }

效果如下:

在这里插入图片描述

欢迎留言~~~


网站公告

今日签到

点亮在社区的每一天
去签到