struts2整合freemarker生成静态页面
1.web.xml加入如下配置 <servlet>
??? ?<servlet-name>JspZSupportServlet</servlet-name>
??? ?<servlet-class>org.apache.struts2.views.JspSupportServlet</servlet-class>
??? ?<load-on-startup>1</load-on-startup>
??? </servlet>
为的是能在ftl文件中使用struts2的标签或者jsp相关的东西
2.新建一个工具类 StaticFreemarker.java-------------------------
public class StaticFreemarker {
?public static void createHTML(ServletContext context,Map<String,Object>data,String templatePath,String targetHtmlPath){
??Configuration cfg = new Configuration();
??cfg.setServletContextForTemplateLoading(context, "/WEB-INF/");
??cfg.setEncoding(Locale.getDefault(), "GB2312");
??Writer out = null;
??try {
???Template t = cfg.getTemplate(templatePath, "GB2312");
???t.setEncoding("GB2312");
???
???//静态页面路径设置
???String htmlPath = context.getRealPath("/html")+"/"+targetHtmlPath;
???File htmlFile = new File(htmlPath);
???out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile),"UTF-8"));
???t.process(data, out);
???
??} catch (Exception e) {
???// TODO Auto-generated catch block
???e.printStackTrace();
??} finally{
???if(out != null){
????try {
?????out.flush();
?????out.close();
????} catch (IOException e) {
?????// TODO Auto-generated catch block
?????e.printStackTrace();
????}
???}
???
??}
??
?}
}
3,创建相应的ftl文件。
4,创建相应的action,一部分代码是
public String createHTML()throws Exception{
??Map<String,Object> data = new HashMap<String,Object>();
??data.put("name", "张三");
??data.put("address", "北京海淀");
??data.put("name1", "李四");
??data.put("address1", "上海");
??
??List<Person> persons = new ArrayList<Person>();
??for(int i = 1; i <= 30; i++){
???Person p = new Person();
???p.setId(i);
???p.setName("张三" + i);???? //data的数据就是上面的ftl模板文件所要用到的数据
???p.setAge("23");
???p.setSex("男");
???persons.add(p);
??}
??data.put("persons", persons);
??StaticFreemarker.createHTML(request.getSession().getServletContext(), data, "success.ftl", "success.html");
??return SUCCESS;
?}
?