<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>2.4.3</version>
</dependency>
# 配置 freemarker 模版引擎 (生成页面)
freemarker:
enabled: true #是否启用freemarker
template-loader-path: classpath:/ftl/ #设定模板的加载路径,多个以逗号分隔
suffix: .ftl #设定模板的后缀
content-type: text/html
check-template-location: true #是否检查模板位置是否存在
cache: false #是否启用模板缓存
charset: UTF-8 #模板编码
import java.io.File;
import java.util.Map;
public interface FreemarkerService {
boolean createStaticHtml(String ftlName, Map<String, Object> params, File outFile);
String createStaticData(String ftlName, Map<Object, Object> params) throws Exception;
}
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
@Service
public class FreemarkerServiceImpl implements FreemarkerService {
@Resource
private Configuration configuration;
@Override
public boolean createStaticHtml(String ftlName, Map<String, Object> params, File outFile) {
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
try {
Template template = configuration.getTemplate(ftlName);
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, params);
inputStream = IOUtils.toInputStream(content, "UTF-8");
FileUtils.forceMkdirParent(outFile);
fileOutputStream = new FileOutputStream(outFile);
IOUtils.copy(inputStream, fileOutputStream);
return true;
} catch (IOException | TemplateException e) {
e.printStackTrace();
return false;
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
@Override
public String createStaticData(String ftlName, Map<Object, Object> params) throws Exception {
try {
Template template = configuration.getTemplate(ftlName);
return FreeMarkerTemplateUtils.processTemplateIntoString(template, params);
} catch (IOException | TemplateException e) {
e.printStackTrace();
throw new Exception(e);
}
}
}