首页 » java

SpringBoot Thymeleaf 实现页面静态化, 生成静态页

   发表于:java评论 (0)   热度:319

springboot + Thymeleaf页面静态化方案一

方案一代码已添加到项目中科运行 直接上代码

package com.blogcommon.utils;

import com.wenhe.blogcommon.config.SystemConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

@Component
public class TplUtil {

    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 手动渲染并异步生成静态文件
     * @param templateName
     * @param model
     * @throws IOException
     */
    public void view(String templateName, Model model) throws IOException {
        view(templateName, model,request(), response());
    }

    /**
     * 手动渲染并异步生成静态文件
     * @param templateName
     * @param model
     * @param response
     * @throws IOException
     */
    public void view(String templateName, Model model, HttpServletResponse response) throws IOException {
        view(templateName, model,request(), response);
    }

    /**
     * 手动渲染并异步生成静态文件
     * @param templateName
     * @param model
     * @param request
     * @param response
     * @throws IOException
     */
    public void view(String templateName, Model model,HttpServletRequest request, HttpServletResponse response) throws IOException {
        String html = this.getHtml(templateName, model,request, response);
        ThreadUtils.execute(() -> create(html, model.getAttribute("uri")));
    }

    /**
     * 生成静态文件
     * @param html
     * @param uriMap
     */
    public void create(String html, Object uriMap){
        try {
            Map<String, String> uri = (Map<String, String>) uriMap;
            if(this.exists(uri.get("url"))){
                return ;
            }

            // 路径的判断,没有自动创建
            File filePath = new File(SystemConfig.publicDir + uri.get("path"));
            if (!filePath.exists()){
                filePath.mkdirs();
            }

            File destFile = new File(SystemConfig.publicDir,  uri.get("url"));
            BufferedWriter writer = new BufferedWriter(new FileWriter(destFile));
            writer.write(html);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param _file
     * @return
     */
    public Boolean exists(String _file){
        File file = new File(SystemConfig.publicDir,  _file);
        // 如果已经有该静态页则不生成
        return file.exists();
    }


    /**
     *
     * @param _file
     */
    public void delete(String _file) {
        // 输出流
        File dest = new File(SystemConfig.publicDir, _file);
        if (dest.exists()) {
            dest.delete();
        }
    }

    private HttpServletRequest request(){
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    private HttpServletResponse response(){
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    /**
     *
     * @param templateName
     * @param model
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    public String getHtml(String templateName, Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        WebContext webContext = new WebContext(request,response,request.getServletContext(),request.getLocale(),model.asMap());
        response.setContentType("text/html;charset=UTF-8");
        String html = templateEngine.process(templateName, webContext);
        response.getWriter().write(html);
        return html;
    }
}

 

 

springboot + Thymeleaf页面静态化方案二

此方案的页面模板用的是 Context context = new Context(); 用这个代码获取内容 Thymeleaf 用 @{}  会报错只能直接写文件的直接链接地址

什么是静态化

静态化是指把动态生成的 HTML 页面变为静态内容保存,以后用户的请求到来,直接访问静态页面,不再经过服务的渲染。

而静态的 HTML 页面可以部署在 nginx 中,从而大大提高并发能力,减小 tomcat 压力。

如何实现静态化

目前,静态化页面都是通过模板引擎来生成,而后保存到 nginx 服务器来部署。常用的模板引擎比如:

  • Freemarker
  • Velocity
  • Thymeleaf

我们之前就使用的 Thymeleaf,来渲染 html 返回给用户。Thymeleaf 除了可以把渲染结果写入 Response,也可以写到本地文件,从而实现静态化。

Thymeleaf 实现静态化

概念

先说下 Thymeleaf 中的几个概念:

  • Context:运行上下文
  • TemplateResolver:模板解析器
  • TemplateEngine:模板引擎

Context

上下文: 用来保存模型数据,当模板引擎渲染时,可以从 Context 上下文中获取数据用于渲染。

当与 SpringBoot 结合使用时,我们放入 Model 的数据就会被处理到 Context,作为模板渲染的数据使用。

TemplateResolver

模板解析器:用来读取模板相关的配置,例如:模板存放的位置信息,模板文件名称,模板文件的类型等等。

当与 SpringBoot 结合时,TemplateResolver 已经由其创建完成,并且各种配置也都有默认值,比如模板存放位置,其默认值就是:templates。比如模板文件类型,其默认值就是 html。

TemplateEngine

模板引擎:用来解析模板的引擎,需要使用到上下文、模板解析器。分别从两者中获取模板中需要的数据,模板文件。然后利用内置的语法规则解析,从而输出解析后的文件。来看下模板引起进行处理的函数:

templateEngine.process("模板名", context, writer);

三个参数:

  • 模板名称
  • 上下文:里面包含模型数据
  • writer:输出目的地的流

在输出时,我们可以指定输出的目的地,如果目的地是 Response 的流,那就是网络响应。如果目的地是本地文件,那就实现静态化了。

而在 SpringBoot 中已经自动配置了模板引擎,因此我们不需要关心这个。现在我们做静态化,就是把输出的目的地改成本地文件即可!

具体实现步骤

相关依赖

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

<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
</dependency>

准备静态原型

thymeleaf文件夹下面新建一个id.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf 静态页面</title>
</head>
<body>
	<h1 th:text="'名字是:' + ${name}"></h1>
	<h1 th:text="'年龄是:' + ${age}"></h1>
	<h1 th:text="'邮箱是:' + ${email}"></h1>
</body>
</html>

接口和实现类

public interface ThymeleafService {
    void createHtml(Long id);
    void deleteHtml(Long id);
}

实现类相关说明

定义一个存放静态文件的目录,这里你也可以写在application.yml文件中,再使用@Value注解也行。

public static final String destPath = "D:/temp/static"; // 自己手动创建一个存在的文件路径

注入模板引擎TemplateEngine

@Autowired
private TemplateEngine templateEngine;

准备加载到页面上的数据,讲道理,这里加载的数据是根据 id 从数据库查询出来的,我这里就写固定了

public Map<String, Object> loadModel(Long id) {
	Map<String, Object> map = new HashMap<>();
	map.put("name", "tellsea");
	map.put("age", 20);
	map.put("email", "3210054449@qq.com");
	return map;
}

接下来就是重点,创建静态页面的方法

/**
 * 创建html页面
 *
 * @param id
 * @throws Exception
 */
public void createHtml(Long id) {
    // 上下文
    Context context = new Context();
    context.setVariables(loadModel(id));
    // 输出流
    File dest = new File(destPath, id + ".html");
    if (dest.exists()) {
        dest.delete();
    }
    try (PrintWriter writer = new PrintWriter(dest, "UTF-8")) {
        // 生成html,第一个参数是thymeleaf页面下的原型名称
        templateEngine.process("id", context, writer);
    } catch (Exception e) {
        log.error("[静态页服务]:生成静态页异常", e);
    }
}
 

这里提供了一个删除静态页面的方法,做戏当然是做全套,删除的接口便于文章后面讲解实战运行

@Override
public void deleteHtml(Long id) {
    // 输出流
    File dest = new File(destPath, id + ".html");
    if (dest.exists()) {
        dest.delete();
    }
}

测试效果

执行createHtmlTest测试类,然后查看D:/temp/static下生成的静态页面,Nice,直接双击生成的Html文件,浏览器就可以访问,效果为带数据的页面,Nice

@RunWith(SpringRunner.class)
@SpringBootTest
public class ThymeleafServiceTest {

    @Autowired
    private ThymeleafService thymeleafService;

    @Test
    public void createHtmlTest() {
        thymeleafService.createHtml(1L);
    }
}

实战分析

上面的实现的功能我们这里把它理解为对于文章详情的静态页,方便下面说明

问题:什么时候调用创建、删除?

新增、更新

我们新增文章、更新文章,完成相应的操作数据库的业务逻辑之后,需要更新静态页面的数据,调用创建的接口,重新创建一个新的即可

thymeleafService.createHtml(1L);

怎么覆盖?仔细看实现类的代码,在创建页面之前,里面有写如果存在,则删除

if (dest.exists()) {
	dest.delete();
}

删除

删除数据库文章之后,直接删除静态页面即可

pageService.deleteHtml(id);

代理静态页面

我们修改nginx,让它对文章详情的请求进行监听,指向本地静态页面,如果本地没找到,才进行反向代理:

server {
    listen       80;
    server_name  www.tellsea.com;

    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Server $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    location /item {
        # 先找本地
        root html; # 这里的html是root安装目录的html文件夹,可以自定义
        if (!-f $request_filename) { #请求的文件不存在,就反向代理
            proxy_pass http://127.0.0.1:8080;
            break;
        }
    }

    location / {
        proxy_pass http://127.0.0.1:9002;
        proxy_connect_timeout 600;
        proxy_read_timeout 600;
    }
}
重启测试:

发现请求速度得到了极大提升,因为访问的是HTML的静态页面了。

相关链接

(。・v・。)
喜欢这篇文章吗?欢迎分享到你的微博、QQ群,并关注我们的微博,谢谢支持。