前些日子看到cms静态化页面有点儿想法,就去简单看了下,做了个简单的demo,现记录如下,供自己翻阅及大家分享指正
话不多少直接上
一. 首先建立一个web工程,在此就不赘述
二. 建立个action(此处我用了webwork)
package com.jack.test.freemarker.cms;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.ActionSupport;
/**
* @author jack.song
* @time 2015年1月7日
*/
public class CmsAction extends ActionSupport {
public String index(){
return SUCCESS;
}
public String convert(){
HashMap<String,Object> data = new HashMap<String,Object>();
List<String> l = new ArrayList<String>();
l.add("hello");
l.add("world");
data.put("hellos", l);
CreateHtmlUtil.createHTML(ServletActionContext.getServletContext(), data, "testCms.ftl", "/testCms.html");
return "login";
}
}
三. 建立一个生产静态页面的工具类
package com.jack.test.freemarker.cms;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
* @author jack.song
* @time 2015年1月7日
*/
public class CreateHtmlUtil {
public static void createHTML(ServletContext context,Map<String,Object> data,String templatePath,String targetHtmlPath){
Configuration freemarkerCfg = new Configuration();
//设置加载模板文件的路径
freemarkerCfg.setServletContextForTemplateLoading(context, "/template/cms");
freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
try {
Template template = freemarkerCfg.getTemplate(templatePath,"UTF-8");
template.setEncoding("UTF-8");
//创建生成静态文件的路径
String htmlPath = context.getRealPath("/cmsfiles")+targetHtmlPath;
File htmlFile = new File(htmlPath);
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
//处理模版并开始输出静态页面
template.process(data, out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}
}
四. 建立一个前端页面,供进行触发静态化动作,和浏览静态页面
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a id="copy_a" href="/testMaven/cms/convert.action" class="btn4">cms生成静态文件</a>
<a id="copy_a" href="/testMaven/cmsfiles/testCms.html" class="btn4">cms访问页面</a>
</body>
</html>
五. 建立模板页面(freemarker)
<html>
<head>
<title>hello!</title>
</head>
<body>
<#list hellos?if_exists as hello>
<p>${hello}</p>
</#list>
</body>
</html>
好了,奏是这么简单,只是简单尝试,简单记录下,没有任何其他意思,转载请注明出处http://blog.youkuaiyun.com/abudexiatian/article/details/43020383