在 Spring boot下配置使用Freemarker
1. Spring boot 的配置文件
在application-dev.properties中添加模板地址
#freemark
freeMarker.templateLoaderPath=classpath:mailTemplate
并且在src下建mailTemplate目录(后续再改成从数据库获得)
2. Freemarker 的配置文件
FreemarkerConfig.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean;
@Configuration
public class FreemarkerConfig
{
@Autowired
private Environment env;
@Bean(value = "freemarkerConfiguration")
public FreeMarkerConfigurationFactoryBean getFreeMarkerConfigurationFactoryBean()
{
FreeMarkerConfigurationFactoryBean freeMarkerConfigurationFactoryBean = new FreeMarkerConfigurationFactoryBean();
String templateLoaderPath = env.getProperty("freeMarker.templateLoaderPath");
freeMarkerConfigurationFactoryBean.setTemplateLoaderPath(templateLoaderPath);
return freeMarkerConfigurationFactoryBean;
}
}
Environment 慎用,最好使用@Value(“${freeMarker.templateLoaderPath}”) 这种形式获取资源变量
3. FreeMarker模板
建在mailTemplate目录下 template.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<table>
<tbody>
<tr>
<td style="width: 150px" class="text-right">ID:</td>
<td>${id }</td>
</tr>
<tr>
<td style="width: 150px" class="text-right">用户:</td>
<td>${createUser}</td>
</tr>
<tr>
<td style="width: 150px" class="text-right">时间:</td>
<td>${createDate}</td>
</tr>
</tbody>
</table>
</body>
</html>
4. 使用方法
templateName=”template.html”
model是模板类中的键值对
例:
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", mailMapDto.getFeedback().getId());
map.put("createUser", mailMapDto.getFeedback().getUsername() + "("
+ mailMapDto.getFeedback().getCreateUser() + ")");
map.put("createDate", mailMapDto.getFeedback().getCreateDate());
执行方法:
public String geFreeMarkerTemplateContent(String templateName,
Map<String, Object> model) {
StringBuffer content = new StringBuffer();
try {
content.append(FreeMarkerTemplateUtils.processTemplateIntoString(
freemarkerConfiguration.getTemplate(templateName), model));
return content.toString();
} catch (Exception e) {
logger.error(
"Exception occured while processing fmtemplate:"
+ e.getMessage(), e);
}
return "";
}
这样就获得拼装好的字符串了
后续在优化成数据库获得模板的