• 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页面既可以使用动态的,也可以是用静态的,根据自己的业务逻辑处理。

  • 相关阅读:
    ES6解构赋值
    ES6中的Symbol类型
    两个列表合并成字典
    python关于列表转为字典的两个小方法
    break、continue和return的使用
    进度条的实现
    md5加密
    dict字典方法
    用户相关的文件、解析以及命令的使用
    linux的根目录
  • 原文地址:https://www.cnblogs.com/se7end/p/9625833.html
Copyright © 2020-2023  润新知