方法一:(這個方法借鑒freemarker的docs文檔Programmer's Guide 的quick start部分,詳細請看相關的文檔。
java 代碼
- public class HtmlTemplateGenerator {
-
- Configuration cfg = null;
-
- public HtmlTemplateGenerator(String templatePath) throws IOException {
- cfg = new Configuration();
- cfg.setDefaultEncoding("UTF-8");
- cfg.setDirectoryForTemplateLoading(new File(templatePath));
- cfg.setObjectWrapper(new DefaultObjectWrapper());
- }
-
-
-
-
-
-
-
-
-
-
- public void create(String ftlTemplate, Map contents, String savePath, String saveFilename) throws IOException, TemplateException {
- Template temp = cfg.getTemplate(ftlTemplate);
-
-
- String realPath = ServletActionContext.getServletContext().getRealPath(savePath);
- System.out.println( saveFilename + ":" + realPath);
- File file = new File(realPath);
- if(!file.exists())
- file.mkdirs();
-
- Writer out = new OutputStreamWriter(new FileOutputStream(realPath + "/" + saveFilename),"UTF-8");
- temp.process(contents, out);
- out.flush();
- }
-
- }
如果用spring,可以將它配置成bean,然后在其他地方使用。第五行的 templatePath 是模版文件的路徑,比如/WEB-INF/template。
action中的使用:HtmlTemplateGenerator.create("html/magazine/search.ftl", null, "/magazine", "search.html"); 其中“html/magazine/search.ftl”是在“/WEB-INF/template”目錄下。這里還需要注意的是。模版文件(search.ftl)中如果還要引用其他文件,它的路徑也是不需要添加總路徑“/WEB-INF/template”。
方法二:繼承webwork的FreemarkerResult,改寫getWriter方法:
不知有無好的法子。
java 代碼
- protected Writer getWriter() throws IOException {
- String savePath = (String) ActionContext.getContext().getSession().get("SAVE_PATH");
- String saveFilename = (String) ActionContext.getContext().getSession().get("SAVE_FILENAME");
- String realPath = ServletActionContext.getServletContext().getRealPath(savePath);
- System.out.println( saveFilename + ":" + realPath);
- File file = new File(realPath);
- if(!file.exists())
- file.mkdirs();
-
- return templateOut = new OutputStreamWriter(new FileOutputStream(realPath + "/" + saveFilename),"UTF-8");
- }
這里的路徑和文件名通過webwork的session傳入,不知有無其他好方法。
如果生成文件的同時還需要看到生成的頁面,則要改寫“doExecute”:
java 代碼
- template.process(model, getWriter());
- template.process(model, super.getWriter());
- templateOut.flush();
生成的文件格式不限于html,可以是其他文件格式,如js,text等。
比較這兩種方法:
方法一:在需要生成分頁文件時,比較合適。
方法二:可以象往常一樣使用,一次需要生成多文件則不適合。
不知各位在做這些項目時,使用甚么好方法。