今年做freemarker与Struts2整合时发现在Action中无法拿到ServletContext,找了好久发现网上好多都是些Struts1中的东西,在google上找了好久,终发现一牛人写的代码,赶紧收藏。并亲自敲了一遍代码,实现过程如下:
首先搭建SSH架构,用的是mysql数据库
http://s11/middle/918966b4tc476ae02f11a&690
写一个新闻添加系统,往数据库中添加新闻然后把添加的新闻实现了静态化处理,其关键代码如下:
Action中
private News news;
public String addNews() {
String path = "//" +
nbi.geNewsId() + ".html";// 生成静态html文件的路径
news.setNdate(new
Date());
nbi.saveOrUpdate(news);
Map<String,
Object> map = new HashMap<String,
Object>();
map.put("news", news);
// 在Struts2
的Action中获取ServletContext对象
ServletContext
context = ServletActionContext.getServletContext();
context.getAttribute("attribute");
// 在Struts2的Action
中获取request
ActionContext
ctx = ActionContext.getContext();
// HttpServletRequest request =
(HttpServletRequest)
//
ctx.get(ServletActionContext.HTTP_REQUEST);
// HttpServletResponse
//
response=(HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);
//
request.getSession().getServletContext();//获取request后也可以用此方法获取ServletContext
// String basePath =
//
request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
OutHtmlFactory.createHtml(map,
path,
context);//调用实现静态化的类
return
SUCCESS;
}
OutHtmlFactory类中代码如下:
public static void createHtml(Map data, String
targetHtmlPath,
ServletContext
context) {
try {
Configuration
conf = new Configuration();
Template temp
= null;
conf.setServletContextForTemplateLoading(context,
"/");
conf.setObjectWrapper(new
DefaultObjectWrapper());
conf.setDefaultEncoding("gbk");//
设置编码
conf.setClassicCompatible(true);//
允许有空值
temp =
conf.getTemplate("temp/news.ftl");// 获得模板对象
String
htmlPath = context.getRealPath("//html") + targetHtmlPath; //
设置保存路径
File htmlFile
= new File(htmlPath);
//
判断路径是否存在,不存在则创建相应路径
if
(!htmlFile.getParentFile().exists()) {
htmlFile.getParentFile().mkdirs();
}
Writer out
= new BufferedWriter(new OutputStreamWriter(
new
FileOutputStream(htmlFile), "gbk"));// 创建输出
temp.process(data,
out);// 执行输出操作
out.flush();
out.close();//
关闭数据流
} catch (Exception e) {
e.printStackTrace();
}
}
运行后最终效果如下:
http://s1/middle/918966b4tc476c1d00f50&690
http://s8/middle/918966b4tc476c1e979d7&690
http://s5/middle/918966b4tc476c23b4724&690
时间过的好快啊 抟摇直上
2012年7月10日
加载中,请稍候......