相信大家都知道了freemarker带给我们的好处,它生成的静态网页让我们的网站能够被百度,google很快搜索到,这就是它最吸引我们的地方了。不过,我好像还没有看见一片文章介绍freemarker与struts1.x结合的文章。不仅如此,很多书尽然说struts1.X不支持freemarker,velocity,这个让我很是失望啊,所有,我就花了一点时间来让struts和freemarker结合
我介绍的是一个完整的web实例:用test.jsp生成对应的静态html/txt页面
环境:struts1.3 freemarker 2.3 mysql5.0 tomcat5.5
另外还要一个包 freemarker for struts1.x 1.0.jar
下载地址:http://chen1255.download.csdn.net/
1.web.xml
<listener>
<listener-class>com.uo.freemarker.FreemarkerListener</listener-class>
</listener>
2.Freemarker实例加载
Action:
import com.uo.freemarker.Freemarker;
import com.uo.freemarker.FreemarkerUtil;
Freemarker free= (Freemarker)(this.getServlet().
getServletContext()).getAttribute(FreemarkerUtil.FREEMARKER);
注意:如果大家用的是ssh框架,如果不能得到ServletContext(),那么请详见《[正解]Ssh获取ServletContext》
http://blog.csdn.net/chen1255/archive/2009/10/27/4734527.aspx
3.初始化
free.init(request, response);
free.process("test.ftl", url, map, "template","gbk");
test.ftl:加载模板
url:生成网页的url
map:就是储存要在ftl中显示的值
这样就可以运行了,原理,我将在下一次文章中发布,大家有什么疑问,可以提出
完整action代码:
public ActionForward doTest(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
TestForm testForm = (TestForm) form;// TODO Auto-generated method stub
String url="";
Date date=new Date();
url="test_"+date.getTime()+".html";
Test t=new Test();
t.setName(testForm.getName());
t.setUrl(url);
List<Test> test = new ArrayList<Test>();
test.add(t);
Map map = new HashMap();
map.put("test", test);
Freemarker free= (Freemarker)(this.getServlet().getServletContext()).getAttribute(FreemarkerUtil.FREEMARKER);
try {
free.init(request, response);
free.process("test.ftl", url, map, "template","gbk");
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
this.service.save(t);
return new ActionForward("/test.do?method=show");
}
完整test.ftl代码
<html>
<body>
<#list test as l>
name:${l.name}
url:${l.url}
</#list>
</body>
</html>
完整Test.Java代码
public class Test implements java.io.Serializable {
// Fields
private Integer id;
private String url;
private String name;
// Constructors
/** default constructor */
public Test() {
}
/** full constructor */
public Test(String url, String name) {
this.url = url;
this.name = name;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}