1.pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
2.代码
2.1 FreemarkerService.java
import java.io.File;
import java.util.Map;
public interface FreemarkerService {
boolean createStaticHtml(String ftlName, Map<Object, Object> params, File outFile);
String createStaticData(String ftlName, Map<Object, Object> params) throws Exception;
String createStaticDataForStr(String ftlStr, Map<Object, Object> params) throws Exception;
}
2.2 FreemarkerServiceImpl.java
import com.yetech.platform.framework.service.FreemarkerService;
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<Object, 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);
}
}
@Override
public String createStaticDataForStr(String ftlName, String ftlStr, Map<Object, Object> params) throws Exception {
try {
Template template = new Template(ftlName, ftlStr, configuration);
return FreeMarkerTemplateUtils.processTemplateIntoString(template, params);
} catch (IOException | TemplateException e) {
e.printStackTrace();
throw new Exception(e);
}
}
}