一个简单的FreeMarker案例(二)

2014-11-24 10:24:11 · 作者: · 浏览: 1
throws ServletException, IOException {

Configuration cfg=new Configuration();

//String path=this.getServletContext().getRealPath("bin/freemarker");

//cfg.setDirectoryForTemplateLoading(new File(path));

cfg.setServletContextForTemplateLoading(this.getServletContext(), "bin/freemarker");

Template tp=cfg.getTemplate("test.ftl");

//因为这个是一个Servlet,所以要用这个,并且由于在Content-Type中配置的字符集都是UTF-8,所以在此处要也设置成UTF-8

Writer out=new OutputStreamWriter(new FileOutputStream(this.getServletContext().getRealPath(".")+"/eg.html"),"utf-8"); //注意的是这里的字符集定要和自己配置的字符集是相同的,否则将出现乱码。并且注意OutputStreamWriter转为Writer的方法。

//PrintWriter out=new PrintWriter(new FileOutputStream(new File(this.getServletContext().getRealPath(".")+"/eg.html")));////如果为servelet则response.getOutputStream()

Map root = new HashMap();

UserInfo u=new UserInfo();

u.setUname("熊师虎");

u.setUage(100);

root.put("u", u);//放入用户的信息,在模板中可以取到用户的信息

List strlist=new ArrayList();

strlist.add("aa");

strlist.add("bb");

strlist.add("cc");

strlist.add("dd");

root.put("strlist", strlist);

root.put("htag", "

我是一级标题

");

try {

tp.process(root, out);

} catch (TemplateException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println("Successfull................");

out.flush();

out.close();

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}

5、配置servlet的url-pattern为:FreeMarkerServlet

6、运行FreeMarkerTest或访问FreeMarkerServlet,用以生成e.html