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包如下