近段时间项目上有个需求:客服在与客户沟通过程中,需要记录他们各式各样的服务日志,例如打电话、发短信,带链接(跳转到其他页面,或者唤起电话服务)、转订单等。接到需求后,和大佬们商量了下就用FreeMarker模板来倒腾下吧~~
应用场景
- 发送邮件
- CMS模块内容存储,便于前端展示
实现方式
pom 依赖
引入freemarker依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
定义配置类
目前有两种方式:(只是初始化不同而已)
- Configuration
- FreeMarkerConfigurer
Configuration
@Service
public class FreeMarkerService {
@Autowired
private Configuration freemarkerConfig;
/**
* 替换模板中变量,并将模板内容转换为字符串
* @param templateName 模板文件名称
* @param paramMap 变量传参
* @return
*/
public String getTemplate2String(String templateName, Map<String, String> paramMap) {
try {
Template template = freemarkerConfig.getTemplate(templateName);
return FreeMarkerTemplateUtils.processTemplateIntoString(template, paramMap);
} catch (IOException | TemplateException e) {
log.error("FreeMarker模板:" + templateName + "转换字符串失败!" + e.getMessage());
e.printStackTrace();
}
return null;
}
}
FreeMarkerConfigurer
@Service
public class FreeMarkerService {
@Autowired
private FreeMarkerConfigurer freemarkerConfig;
/**
* 替换模板中变量,并将模板内容转换为字符串
* @param templateName 模板文件名称
* @param paramMap 变量传参
* @return
*/
public String getTemplate2String(String templateName, Map<String, String> paramMap) {
try {
Template template = freemarkerConfig.getConfiguration().getTemplate(templateName);
return FreeMarkerTemplateUtils.processTemplateIntoString(template, paramMap);
} catch (IOException | TemplateException e) {
log.error("FreeMarker模板:" + templateName + "转换字符串失败!" + e.getMessage());
e.printStackTrace();
}
return null;
}
}
调用方
- 在resources/templates下有mail.ftl模板
@Service
@AllArgsConstructor
public class SendMail {
private final FreeMarkerService freeMarkerService;
public void send() {
//do something
freeMarkerService.getTemplate2String("mail.ftl", iVo)
}
}
遇到的问题
Template not found 找不到模板
具体错误内容如下:
freemarker.template.TemplateNotFoundException: Template not found for name "changeStatus.ftl".
原因:服务启动日志中实际上已经提示了,FreeMarker模板默认应该放在 classpath:/templates/,即resources/templates中。
o.s.b.a.f.FreeMarkerAutoConfiguration : Cannot find template location(s): [classpath:/templates/] (please add some templates, check your FreeMarker configuration, or set spring.freemarker.checkTemplateLocation=false)