Thymeleaf静态化页面

前置知识

什么是Thymeleaf静态模板引擎

为什么要做页面静态化?

在生产环境中,业务复杂多变,我们需要保证系统要求高可用,高并发。
如果系统的某一个页面需要返回大量的数据,而且该页面经常被大量请求访问,那么该页面的数据渲染问题就会变成系统性能的短板,同时大量的请求会对数据库造成极大的压力。
这个时候,我们通过后端获取数据,然后响应前端渲染数据的方法就很难解决这个问题。

Redis缓存?

Redis是一款基于缓存的数据库,可以快速地响应大量数据,可以使用Redis作为缓存来响应该页面的数据,保证该页面的访问性能吗?
不行!
因为Redis虽然是基于缓存的,但是它只适用于存放少量数据,如果数据量过大,很容易造成Redis缓存崩溃,然后所有请求打在数据库上,造成数据库宕机。
所以缓存不是万能的。

页面静态化技术

后端访问数据,然后渲染前端的方法会使系统性能下降,那么我们就可以使用页面静态化技术,就是将动态生成的HTML文件,变成一个静态的HTML文件保存起来,然后让用户访问这个静态页面。
这样就省去了系统请求后端的和前端渲染数据的时间,大大提高了系统的访问效率。

怎么实现页面静态化?

目前,静态化页面都是通过模板引擎来生成,常用的模板引擎有:

  • Freemarker
  • Velocity
  • Thymeleaf

Thymeleaf静态化技术

准备工作

该项目的环境搭建,Thymeleaf前端页面渲染,都已经在Thymeleaf静态模板引擎中准备好了。

编写Service层代码

我们将页面静态化的代码逻辑放在Service层。

@Service
public class ThymeleafService {

    @Autowired
    private TemplateEngine templateEngine;

    public void createHtml() throws FileNotFoundException {
        User user = new User(1,"张三",20);
        //创建thymeleaf上下文对象
        Context context = new Context();
        //把数据放入上下文对象
        context.setVariable("user",user);
        context.setVariable("msg","Hello, Thymeleaf!");
        //创建一个输出流
        PrintWriter writer = new PrintWriter(new File("G:\\temp\\html\\"+user.getId()+".html"));
        //生成静态页面
        templateEngine.process("hello",context,writer);
    }
}

编写Web层代码

我们修改Web的代码逻辑,增加页面静态化的方法。

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private ThymeleafService thymeleafService;

    @GetMapping("hello")
    public String hello(Model model) throws FileNotFoundException {
        User user = new User(1,"张三",20);
        model.addAttribute("user",user);
        model.addAttribute("msg", "Hello, Thymeleaf!");
        //调用Service层的方法,创建HTML文件
        thymeleafService.createHtml();
        return "hello";
    }
}

功能测试

启动项目,访问/user/hello接口,我们就发现在G:\temp\html目录下生成了一个1.html文件。

hello.html模板文件

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello页面</title>
</head>
<body>
    <h1 th:text="${user.name}"></h1>
    <h1 th:text="${msg}"></h1>
</body>
</html>

1.html静态页面文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello页面</title>
</head>
<body>
    <h1>张三</h1>
    <h1>Hello, Thymeleaf!</h1>
</body>
</html>
发布了76 篇原创文章 · 获赞 82 · 访问量 8160

猜你喜欢

转载自blog.csdn.net/qq_45193304/article/details/105091059