public class PlaceHolderTest {
@Test
public void test1(){
System.out.println(MessageFormat.format("我是{0},我要{1}、{1}","中国人","努力奋斗"));
}
@Test
public void test2() {
String str = "我是%1s";
System.out.println(String.format(str,"工程人"));
}
}
public class CommonUtils {
@SneakyThrows
public static String freemarkerTemplateReplace(String templateContent, Map<String, Object> data) {
Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
stringTemplateLoader.putTemplate(CommonConstants.FREEMARKER_TEMPLATE_NAME, templateContent);
configuration.setTemplateLoader(stringTemplateLoader);
Template template = configuration.getTemplate(CommonConstants.FREEMARKER_TEMPLATE_NAME, CommonConstants.UTF_8);
StringWriter stringWriter = new StringWriter();
template.process(data, stringWriter);
return stringWriter.toString();
}
@SneakyThrows
public static String freemarkerTemplateReplaceFile(String ftlName, Map<String, Object> dataMap) {
Configuration configuration = new Configuration();
configuration.setClassForTemplateLoading(CommonUtils.class, "/templates");
configuration.setDefaultEncoding(CommonConstants.UTF_8);
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
Template template = configuration.getTemplate(ftlName + ".ftl");
Writer writer = new StringWriter();
template.process(dataMap, writer);
return writer.toString();
}
}
public class FreemarkerTest {
@Test
public void testString() {
String template = "我叫${name},今年${age}";
Map<String, Object> objectMap = new HashMap() {{
put("name", "小明");
put("age", "29");
}};
String str = CommonUtils.freemarkerTemplateReplace(template, objectMap);
System.out.println(str);
}
@Test
@SneakyThrows
public void testFile(){
String templateName = "StudentEmail";
List<Student> studentList = new ArrayList<>(3);
Student student = new Student(1,"小明",18);
Student student2 = new Student(2,"小红",28);
Student student3 = new Student(3,"老王",38);
studentList.add(student);
studentList.add(student2);
studentList.add(student3);
Map<String, Object> dataMap = new HashMap(1){{
put("studentList", studentList);
}};
String str = CommonUtils.freemarkerTemplateReplaceFile(templateName, dataMap);
System.out.println(str);
@Cleanup Writer writer = new FileWriter("target/test1.html");
writer.write(str);
writer.flush();
}
}
- 通过文件模版调用;示例:StudentEmail.ftl
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>student email test freemarker</title>
</head>
<body>
<table border="1" cellspacing="0" cellpadding="0">
<tr align="center" style="background-color: peachpuff;height: 32px;line-height: 32px;font-weight: 600;">
<th style="width: 90px;">ID</th>
<th style="width: 90px;">姓名</th>
<th style="width: 90px;">年龄</th>
</tr>
<#list studentList as item>
<tr align="center">
<td>${item.id}</td>
<td>${item.name}</td>
<td>${item.age}</td>
</tr>
</#list>
</table>
</body>
</html>