2021与蓝度共同重构项目,服务端
liuhaonan
2022-10-24 c5ef81f257e0176cdcfce034779a15f544d6694c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.sandu.ximon.admin.utils;
 
 
import java.io.*;
import java.util.Map;
 
import org.springframework.core.io.ClassPathResource;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
 
/**
 * @program: machine-fast
 * @description: thymeleaf渲染工具类
 * @author: YSS
 * @create: 2019-09-09 17:55
 **/
public class HtmlTemplateUtils {
 
    private final TemplateEngine templateEngine = new TemplateEngine();
 
    // 解析模板
    public String render(String template, Map<String, Object> params){
        Context context = new Context();
        context.setVariables(params);
        return templateEngine.process(template, context);
    }
 
    // 文件读取包装方法
    public String renderPath(String path, Map<String, Object> params){
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        String body = "";
        try {
//            File file = ResourceUtils.getFile(path);
            ClassPathResource classPathResource = new ClassPathResource(path);
            inputStream = classPathResource.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String s = "";
            while ((s = bufferedReader.readLine()) != null){
                body += s + "\n";
            }
            return this.render(body, params);
        } catch (IOException e) {
            return body;
        }finally {
            try{
                if(bufferedReader != null){
                    bufferedReader.close();
                }
                if(inputStreamReader != null){
                    inputStreamReader.close();
                }
                if(inputStream != null){
                    inputStream.close();
                }
            }catch (IOException e){
            }
        }
    };
}