美文网首页
在spring boot下使用Freemarker替换模板内容

在spring boot下使用Freemarker替换模板内容

作者: 侧耳倾听y | 来源:发表于2021-07-16 16:58 被阅读0次
    • 依赖
            <dependency>
                <groupId>org.freemarker</groupId>
                <artifactId>freemarker</artifactId>
            </dependency>
    
    • 工具类
    @Slf4j
    public class FreemarkerUtils {
    
        private static final Configuration cfg;
    
        private FreemarkerUtils() {
        }
    
        static {
            cfg = new Configuration(Configuration.getVersion());
            cfg.setDefaultEncoding("UTF-8");
            // FreeMarker会默认格式化数字,这样设置不再格式化数字
            cfg.setNumberFormat("#");
        }
    
        public static String processTemplate(String myTemplate, Map<String, Object> map) {
            String result = null;
            String name = "template";
    
            try {
                StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
                stringTemplateLoader.putTemplate(name, myTemplate);
                cfg.setTemplateLoader(stringTemplateLoader);
                Template template = cfg.getTemplate(name, "UTF-8");
                StringWriter out = new StringWriter();
                template.process(map, out);
                out.flush();
                result = out.toString();
                out.close();
            } catch (Exception e) {
                log.error("FreemarkerUtils processTemplate error", e);
            }
            return result;
        }
    
    }
    
    • 使用
            Map<String, Object> templateMap = new HashMap<>(8);
            templateMap.put("statisticDate",123456);
            String templateStr = "i am ${statisticDate}";
            String str = FreemarkerUtils.processTemplate(templateStr, templateMap);
    

    相关文章

      网友评论

          本文标题:在spring boot下使用Freemarker替换模板内容

          本文链接:https://www.haomeiwen.com/subject/wkybpltx.html