2019獨角獸企業重金招聘Python工程師標準>>>
其對應的模板文件:
<table style="text-align:center;FONT-SIZE: 11pt; WIDTH: 600px; FONT-FAMILY: 宋體; BORDER-COLLAPSE: collapse" borderColor=#3399ff cellSpacing=0 cellPadding=0 align=center border=1><tr><td><b>編號</b></td><td><b>用戶名</b></td><td><b>密碼</b></td><td><b>性別</b></td><td><b>年齡</b></td></tr><#list personList as person><tr><td>${person.id}</td><td>${person.name}</td><td>${person.password}</td><td>${person.sex}</td><td>${person.age}</td></tr></#list></table>
Action:
public class LoginAction extends ActionSupport {private String msg;@Overridepublic String execute() {StaticFreemarker sf = new StaticFreemarker();List<Person> persons = new ArrayList<Person>();for(int i=1;i<=23;i++){Person p = new Person();p.setId(i);p.setName("darkness" + i);p.setAge("23");p.setPassword("sky" + i);p.setSex("man");persons.add(p);}Map<String,List<Person>> map = new HashMap<String,List<Person>>();map.put("personList", persons);String htmlfile = "personList.html";try {sf.init("personList.ftl", htmlfile, map, "index");} catch (IOException e) {e.printStackTrace();} catch (TemplateException e) {e.printStackTrace();}this.msg = htmlfile;return Action.SUCCESS;}public String getMsg() {return msg;}}
struts.xml配置文件:
<struts><package name="tutorial" extends="struts-default"><action name="login" class="org.darkness.freemarker.action.LoginAction"><result type="redirect">/${msg}</result></action></package>
</struts>
通過Freemarker生成靜態頁面的關鍵代碼如下:
public class StaticFreemarker {/*** 初始化模板引擎* * @param ftl 模板名稱* @param htmlName 需要生成html頁面的名稱* @param map 模板中需要的參數集合* @param relativePath 模板相對于根路徑的相對路徑* @throws IOException* @throws TemplateException*/@SuppressWarnings("unchecked")public void init(String ftl, String htmlName, Map map, String relativePath)throws IOException, TemplateException {Configuration freemarkerCfg = new Configuration();freemarkerCfg.setServletContextForTemplateLoading(ServletActionContext.getServletContext(), "/" + relativePath);freemarkerCfg.setEncoding(Locale.getDefault(), "gbk");Template template = freemarkerCfg.getTemplate(ftl);template.setEncoding("gbk");String path = ServletActionContext.getServletContext().getRealPath("/");File htmlFile = new File(path + htmlName);Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "gbk"));template.process(map, out);out.flush();out.close();}}
說明:需要添加的jar包如下