FreeMarker页面静态化使用小结
1.前置准备(此处为SpringBoot项目)
(1)依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
(2)配置文件[无参考意义,具体配置需结合实际]
## freemarker模板
spring.freemarker.template-loader-path=classpath:/templates/,file:D:\\WorkSpace\\xxx\\src\\main\\webapp\\WEB-INF\\views\\
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.ftl
spring.freemarker.settings.template_exception_handler=ignore
2.生成页面代码
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.springframework.stereotype.Service;
import java.io.*;
import java.util.Map;
import java.util.Properties;
@Service
public class FreemarkerService {
private static final Configuration cfg;
static {
cfg = new Configuration(Configuration.VERSION_2_3_28);
Properties properties = new Properties();
InputStream inputStream = FreemarkerService.class.getResourceAsStream("/application.properties");
InputStreamReader inputStreamReader = null;
try {
inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
properties.load(inputStreamReader);
String templatePath = properties.getProperty("spring.freemarker.template-loader-path");
String[] split = templatePath.split(",");
templatePath = split[1].replace("file:", "");
cfg.setDirectoryForTemplateLoading(new File(templatePath));
cfg.setDefaultEncoding("utf-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void createHtml(String modeName, String targetFileName, String folder, Map<String, Object> params) throws Exception {
Writer out = null;
File fileDir = new File(folder);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
String outFile = folder + File.separator + targetFileName;
try {
File file = new File(outFile);
if (file.exists()) {
file.delete();
}
file.createNewFile();
Template template = cfg.getTemplate(modeName);
out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
template.process(params, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != out) {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
4.模拟调用
a.main方法调用
public static void main(String[] args) throws Exception {
Map<String, Object> params = new HashMap<String, Object>();
params.put("title", "freemarker&springboot");
params.put("author", "tony");
params.put("publishTime", "2018-02-09");
params.put("seeNum", "888");
params.put("imgPath", "http://5b0988e595225.cdn.sohucs.com/images/20181208/2c34c5244b5646418e658eacec7655df.jpeg");
params.put("content", "freemarker静态页面生成");
FreemarkerService.createHtml("test.ftl", "test.html", "D:\\freemarker", params);
}
b.请求调用
import com.alibaba.fastjson.JSONObject;
import com.morewis.util.HttpServletUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
@Controller()
public class NewsFreemarkerController {
@Value("${path}")
private String folder;
@Autowired
PageDataService pageDataService;
@RequestMapping("/createHtml")
@ResponseBody
public String createHtml() {
HttpServletRequest request = HttpServletUtil.getRequest();
Map<String, Object> params = new HashMap<String, Object>();
params.put("dao", pageDataService);
String pageNumber = request.getParameter("pageNumber");
String domainName = request.getParameter("domainName");
String targetFileName = "index.html";
String folderTemp = folder + File.separator + domainName;
JSONObject jsonObject = new JSONObject();
try {
FreemarkerService.createHtml("template\\test.ftl", targetFileName, folderTemp, params);
jsonObject.put("succes", true);
jsonObject.put("message", "创建成功");
} catch (Exception e) {
e.printStackTrace();
jsonObject.put("succes", false);
jsonObject.put("message", "创建失败:"+e.getMessage());
}
return jsonObject.toJSONString();
}
}
4.模板代码(针对方案a)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name='viewport'
content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
<title>Freemarker生成静态页面Demo展示</title>
<style type="text/css">
article {
padding: 20px;
}
address {
font-style: normal;
text-align: right;
width: 100%;
color: #999999;
}
.author {
float: left;
}
.seeIcon {
padding: 0px 12px;
background: url(imgs/see.png) no-repeat;
}
.seeNum {
width: 100%;
}
.img {
width: 380px;
height: 380px;
}
</style>
</head>
<body>
<article>
<h2>${title}</h2>
<address>
<span class="author">${author} ${publishTime}</span>
<span class="seeIcon"></span>
<span class="seeNum">${seeNum}</span>
</address>
<img src="${imgPath}" class="img"/>
<p>${content}</p>
</article>
</body>
</html>
本篇仅作记录,如有错误,还望请大佬指教