thymeleaf 實現靜態化頁面


1、什么是頁面靜態化 靜態化

  是指把動態生成的HTML頁面變為靜態內容保存,以后用戶的請求到來,直接訪問靜態頁面,不再經過服務的渲染。 而靜態的HTML頁面可以部署在nginx中,從而大大提高並發能力,減小tomcat壓力。

2、目前,靜態化頁面都是通過模板引擎來生成,而后保存到nginx服務器來部署。常用的模板引擎比如:

- Freemarker

- Velocity -

Thymeleaf

這里采用Thymeleaf!!

 

3、查看項目結構

 

4、引入依賴,配置文件

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.12.RELEASE</version>
        <relativePath/>
    </parent>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

配置application.yml文件

server:
  port: 8080

5、配置啟動類

@SpringBootApplication
public class DemoApp {
    public static void main(String[] args) {
        SpringApplication.run(DemoApp.class,args);
    }
}

6、創建controller、service、user對象、utils工具類, 靜態頁面

創建controller:

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

    @Autowired
    private HtmlService htmlService;

    @GetMapping("{id}.html")
    public String get(Model model,@PathVariable("id") Long id){
        User user = new User();
        user.setName("張三");
        model.addAttribute("user",user);

        // 頁面靜態化
        this.htmlService.asyncExcute(id);

        return "index";
    }
}

創建service,命名為HtmlService:

import com.leyou.utils.ThreadUtils;
import org.example.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.Map;

@Service
public class HtmlService {

    @Autowired
    private TemplateEngine templateEngine;

    private static final Logger LOGGER = LoggerFactory.getLogger(HtmlService.class);

    /**
     * 創建html頁面
     * @param id
     * @throws Exception
     */
    public void createHtml(Long id) {

        PrintWriter writer = null;
        try {
            // 獲取頁面數據
            User user = new User();
            user.setName("張三");

            // 創建thymeleaf上下文對象
            Context context = new Context();
            // 把數據放入上下文對象
            context.setVariable("user",user);

            // 創建輸出流 D:\nginx-1.18.0\html
            File file = new File("D:\\nginx-1.18.0\\html\\user\\" + id + ".html");
            writer = new PrintWriter(file);

            // 執行頁面靜態化方法
            templateEngine.process("index", context, writer);

        } catch (Exception e) {
            LOGGER.error("頁面靜態化出錯:{},"+ e, id);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    /**
     * 新建線程處理頁面靜態化
     * @param spuId
     */
    public void asyncExcute(Long spuId) {
        ThreadUtils.execute(()->createHtml(spuId));
        ThreadUtils.execute(new Runnable() {
            @Override
            public void run() {
                createHtml(spuId);
            }
        });
    }
}

創建user類

public class User {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

創建ThreadUtils工具類

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadUtils {

    private static final ExecutorService es = Executors.newFixedThreadPool(10);

    public static void execute(Runnable runnable) {
        es.submit(runnable);
    }
}

在resources/templates下創建index.html : 

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

7、需要nginx做代理,配置如下

location /user {
     root html;
             
     if (!-f $request_filename) { #請求的文件不存在,就反向代理
         proxy_pass http://127.0.0.1:8080;
         break;
     }
}

配置好后重啟nginx,指令: nginx -s reload

 

8、測試

訪問 http://localhost/user/1.html

 

  

檢查D:\nginx-1.18.0\html\user目錄下是否有靜態化的html文件!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM