• springboot使用Freemark生成动态页面工具


    引入pom

    1. <dependency>
    2. <groupId>org.springframework.bootgroupId>
    3. <artifactId>spring-boot-starter-freemarkerartifactId>
    4. dependency>

    代码:

    1. import com.alibaba.fastjson.JSON;
    2. import com.fuing.tea.commons.enums.TemplateEnum;
    3. import freemarker.template.Configuration;
    4. import freemarker.template.Template;
    5. import org.slf4j.Logger;
    6. import org.slf4j.LoggerFactory;
    7. import java.io.BufferedWriter;
    8. import java.io.File;
    9. import java.io.StringWriter;
    10. /**
    11. * @author Garcia
    12. * @date 2022/8/25 14:13
    13. */
    14. public class FreemarkerUtil {
    15. private static Configuration configuration;
    16. private static final String BASE_PACKAGE_PATH = File.separator + "templates";
    17. static Logger logger = LoggerFactory.getLogger(FreemarkerUtil.class);
    18. static {
    19. configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
    20. // 第二步:设置模板文件所在的路径。
    21. configuration.setClassForTemplateLoading(FreemarkerUtil.class, BASE_PACKAGE_PATH);
    22. // 第三步:设置模板文件使用的字符集。一般就是utf-8.
    23. configuration.setDefaultEncoding("utf-8");
    24. }
    25. public static String createHtml(TemplateEnum tlf, Object model) throws Exception {
    26. logger.info("根据模板生成内容, 模板:{}, model={}", tlf.getName(), JSON.toJSONString(model));
    27. StringWriter sw = null;
    28. BufferedWriter writer = null;
    29. try {
    30. Template template = configuration.getTemplate(tlf.getName());
    31. sw = new StringWriter();
    32. writer = new BufferedWriter(sw);
    33. template.process(model, writer);
    34. }finally {
    35. if (sw!=null){
    36. sw.close();
    37. }
    38. if (writer!=null){
    39. writer.close();
    40. }
    41. }
    42. return sw.toString();
    43. }
    44. }
    1. /**
    2. * @author Garcia
    3. * @date 2022/8/25 14:18
    4. */
    5. public enum TemplateEnum {
    6. /**
    7. * 报告模板
    8. */
    9. REVIEW_REPORT("reviewTemplate.ftl","报告模板");
    10. private String name;
    11. private String desc;
    12. TemplateEnum(String name, String desc){
    13. this.name = name;
    14. this.desc = desc;
    15. }
    16. public String getName() {
    17. return name;
    18. }
    19. }

     具体怎么使用,需要自己看解析方式

  • 相关阅读:
    QT开发实例之常用控件(上)
    Docker 与 WasmEdge 合作,发布 WebAssembly 支持
    JAVA【注解】 自定义注解
    数组(1)
    【物联网】Arduino+ESP8266物联网开发(二):控制发光二极管 按钮开关控制开关灯
    一种基于遗传算法与神经网络算法(GA-BP)的新冠肺炎模型预测-含Matlab代码
    MySQL5.5版本安装详细讲解
    WPF项目实战布局--通用固件下载 C#
    QT-QTableWidget中的cell和item的区别
    KNN算法学习笔记
  • 原文地址:https://blog.csdn.net/Qensq/article/details/132904957