使用FreeMarker做文本替换
引入
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>${freemarker.version}</version>
</dependency>
这里的version做好是 2.3.22以上的版本
代码
import cn.hutool.core.util.StrUtil;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.SneakyThrows;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 使用说明 ${name!12312312} 代表默认值
* 支持自定义日期格式newDate为约定 ${newDate?string("yyyy-MM-dd HH:mm:ss")
* 普通字符直接替换${code}
* @author zlf
* @date 2023/6/19 6:56 PM
* @desc
*/
public class ContentReplaceUtil {
public static String NOW_DATE = "newDate";
@SneakyThrows
public static String replaceWord(String content, Map<String, Object> params) {
if (StrUtil.isEmpty(content)){
return null;
}
if (content.contains(NOW_DATE)){
params.put("newDate",new Date());
}
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
stringTemplateLoader.putTemplate("test.ftl", content);
Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
cfg.setTemplateLoader(stringTemplateLoader);
Template template = cfg.getTemplate("test.ftl");
String finalContent = FreeMarkerTemplateUtils.processTemplateIntoString(template, params);
return finalContent;
}
public static void main(String[] args) throws IOException, TemplateException {
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
String b ="您好${name!12312312},${newDate?string("yyyy-MM-dd HH:mm:ss")}欢迎您12321312312312312312 ${code}";
stringTemplateLoader.putTemplate("test.ftl", b);
Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
cfg.setTemplateLoader(stringTemplateLoader);
Template template = cfg.getTemplate("test.ftl");
Map<String, Object> data = new HashMap<>();
data.put("name","小帅");
data.put("newDate", new Date());
data.put("code", "12123123123");
String s = FreeMarkerTemplateUtils.processTemplateIntoString(template, data);
System.out.println(s);
}
}
讲解
中文官方文档 freemarker.foofun.cn/toc.html
- freemarker 支持时间格式替换,这里自定义key,例如newDate,这样就知道这是一个需要替换当前时间格式的功能。
- 支持默认值功能使用说明 ${name!12312312} 代表默认值,如果map里面name为空则,默认使用!之后的值
- 普通字符直接替换${code}