zoukankan      html  css  js  c++  java
  • Freemarker生成静态资源文件

    项目是SpringBoot + Freemarker的。

    所有的页面都是Freemarker文件写的,有些页面数据比较多,打开比较慢,所以做了一个静态页面。

    因为本身所有的页面都是FTL文件,所以模板就地取材,不用自己另外去写。

    核心处理spring.ftl文件中的内容就可以了。

    spring.ftl文件中都是以springMacroRequestContext对象来处理的。只要找到这个对象的值是从那里来的就行了。

    AbstractTemplateView类中:

    关键部分代码:

    Map<String, Object> ftlMap = new HashMap<String, Object>();
    ftlMap.put(AbstractTemplateView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE, new RequestContext(request, response, request.getServletContext(), null));
    ftlMap.put("model", "需要填充的数据,数据类型可以是map,model类等");
    String ftlPath = "模板.ftl",
           htmlPath = "静态文件.html");
    boolean cr = FreemarkerUtil.createHtml(ftlMap, ftlPath, htmlPath);

    其中request和response:

    HttpServletRequest request, HttpServletResponse response

    FreemarkerUtil代码:

    public class FreemarkerUtil {
    
        public static String ENCODING = "UTF-8";
        public static String LOCATION_PATH = FileUtil.LOCATION_PATH;
    
        public static String FTL_ROOT_PATH = "/templates";
    
        private static Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
        static {
            configuration.setDefaultEncoding(ENCODING);
            // 设置模板装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载。
            // 加载模板文件,放src/main/resources在下
            configuration.setClassForTemplateLoading(FreemarkerUtil.class, FTL_ROOT_PATH);
            // 设置异常处理器
            configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
        }
    
        public static boolean createHtml(Map<String, Object> dataMap, String ftlPath, String htmlPath) {
            boolean r = false;
            try {
                // 加载需要装填的模板
                Template template = null;
                // 定义Template对象
                template = configuration.getTemplate(ftlPath);
                String filePath = LOCATION_PATH + File.separator + htmlPath;
                File outFile = new File(filePath);
                Writer out = null;
                out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), ENCODING));
                template.process(dataMap, out);
                out.close();
                r = true;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TemplateException e) {
                e.printStackTrace();
            }
            return r;
        }
    }

    ftl页面既可以使用动态的,也可以是用静态的,根据自己的业务逻辑处理。

  • 相关阅读:
    c++ 动态判断基类指针指向的子类类型(typeid)
    qt在GUI显示时,将调试信息输出到控制台的设置
    Qt库版查询
    Qt动态库静态库的创建、使用、多级库依赖、动态库改成静态库等详细说明
    ICMP timestamp 请求响应漏洞
    linux 防火墙 ufw使用
    MySQL--binlog和relay log的生成和删除
    SSD 相关基础知识
    python36--将数据保存为excel
    MySQL 5.7并发复制和mysqldump相互阻塞引起的复制延迟
  • 原文地址:https://www.cnblogs.com/se7end/p/9625833.html
Copyright © 2011-2022 走看看