一、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
二、封装
public static String parseContent(String content, Map<String, Object> dataMap) {
try {
String tempname = hashKeyForDisk(content);
Configuration configuration = new Configuration();
configuration.setNumberFormat("#");
StringTemplateLoader stringLoader = new StringTemplateLoader();
stringLoader.putTemplate(tempname, content);
freemarker.template.Template template = new freemarker.template.Template(tempname, new StringReader(content));
StringWriter stringWriter = new StringWriter();
template.process(dataMap, stringWriter);
configuration.setTemplateLoader(stringLoader);
content = stringWriter.toString();
}catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Template parsing failed");
}
return content;
}
public static String hashKeyForDisk(String key) {
String cacheKey;
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(key.getBytes());
cacheKey = bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
cacheKey = String.valueOf(key.hashCode());
}
return cacheKey;
}
private static String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
三、调用
public static void main(String[] args) {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("name", "Brady");
String templateContent="hello ${name}!";
System.out.println(parseContent(templateContent,paramMap));
}