优秀的编程知识分享平台

网站首页 > 技术文章 正文

FreeMarker Java 使用(java freemarker word)

nanyue 2024-08-01 22:51:10 技术文章 11 ℃


官方网站

https://freemarker.apache.org/index.html


github地址

https://github.com/apache/freemarker


介绍

FreeMarker是一个模板引擎:即一种基于模板和要改变的数据,并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。 它不是面向最终用户的Web页面编辑器,而是程序员在其Web应用程序中使用的工具。使用FreeMarker作为模板引擎的好处是它可以与您的Web应用程序代码分离,从而使开发过程更加清晰和简单。此外,由于模板是纯文本文件,因此它们可以用任何文本编辑器打开和修改,这使得它们易于管理和维护。 FreeMarker与容器无关,因为它并不知道HTTP或Servlet。FreeMarker同样可以应用于非Web应用程序环境。 FreeMarker的特点包括:

  1. 强大的模板语言:所有常用的指令:include、if/elseif/else、循环结构等;
  2. 通用数据模型:可以直接使用JavaBean和Collection类型,以及其他POJO(Plain Old Java Objects)作为模板中的变量;
  3. 可扩展性:可以通过继承现有类并重写方法来扩展其功能;
  4. 独立于Web容器:可以在没有Web服务器的情况下独立运行,也可以集成到现有的Web应用程序中。 通过使用FreeMarker,您可以轻松地将动态内容添加到静态HTML页面中,并且可以在整个网站中重复使用相同的元素,从而提高工作效率。

gradle 添加依赖

搜索地址

https://mvnrepository.com/artifact/org.freemarker/freemarker

dependencies {
    implementation "org.freemarker:freemarker:2.3.32"
}

简单模版

获取名称1:${name1}
获取名称2:${name2}

代码

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class MainApplication {
    public static void main(String[] args) throws Exception {
        Configuration config = new Configuration();
        config.setObjectWrapper(new DefaultObjectWrapper());
        Template template = config.getTemplate("flt/test.flt", "UTF-8");
        String outPath = "gen";
        File file = new File(outPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outPath + "/TestGen.txt"), "UTF-8"));

        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("name1", "测试名称1");
        dataModel.put("name2", "测试名称2");

        template.process(dataModel, out);
        out.flush();
        out.close();
    }
}

生成文件

获取名称1:测试名称1
获取名称2:测试名称2

实际项目使用,常用于模版代码生成 比如 Exception,Bean 等

列表使用

<#list datas as param>
 ${param.name}
</#list>


代码

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ListExample {
    public static void main(String[] args) throws Exception {
        Configuration config = new Configuration();
        config.setObjectWrapper(new DefaultObjectWrapper());
        Template template = config.getTemplate("flt/list.flt", "UTF-8");
        String outPath = "gen";
        File file = new File(outPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outPath + "/list.txt"), "UTF-8"));

        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("datas", List.of(
                Map.of("name", "游客1"),
                Map.of("name", "游客2"),
                Map.of("name", "游客3")
        ));
        template.process(dataModel, out);
        out.flush();
        out.close();
    }
}


生成内容

 游客1
 游客2
 游客3


实战案例

模板

/**
 * 系统中的错误信息
 */
public enum ErrorInfo {
<#list infos as param>
    /**
     * ${param.message}
     */
    ${param.name}(new MyException("${param.message}",${param.code})),
</#list>

    ;
    private final  MyException exception;

    ErrorInfo(MyException e) {
        exception = e;
    }

    public MyException getException() {
        return exception;
    }
}



public class Entity {
    public String name;

    public String message;

    public String code;


    public Entity(String name, String message, int code) {
        this.name = name;
        this.message = message;
        this.code = String.valueOf(code);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}


生成代码

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainApplication {
    public static void main(String[] args) throws Exception {
        List<Entity> entities = new ArrayList<>();
        entities.add(new Entity("UNKNOWN_ERROR", "Unknown Error", -1));
        entities.add(new Entity("SYSTEM_ERROR", "Systen Error", 500));
        entities.add(new Entity("UNAUTHORIZED", "Unauthorized", 401));
        Map<String, Object> params = new HashMap<>();
        params.put("infos", entities);
        genJava(params);
    }

    public static void genJava(Map<String, Object> params) throws Exception {
        Configuration config = new Configuration();
        config.setObjectWrapper(new DefaultObjectWrapper());
        Template template = config.getTemplate("flt/exception.flt", "UTF-8");
        boolean windows = File.separatorChar == '\\';
        if (windows) {

        } else {
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("gen/ErrorInfo.java"), "UTF-8"));
            template.process(params, out);
            out.flush();
            out.close();
        }
    }
}


生成内容

/**
 * 系统中的错误信息
 */
public enum ErrorInfo {
    /**
     * Unknown Error
     */
    UNKNOWN_ERROR(new MyException("Unknown Error",-1)),
    /**
     * Systen Error
     */
    SYSTEM_ERROR(new MyException("Systen Error",500)),
    /**
     * Unauthorized
     */
    UNAUTHORIZED(new MyException("Unauthorized",401)),

    ;
    private final  MyException exception;

    ErrorInfo(MyException e) {
        exception = e;
    }

    public MyException getException() {
        return exception;
    }
}


github 完整案例

https://github.com/code-mm/freemarker-example.git

Tags:

最近发表
标签列表