1.下载freemarker,解压,在工程中加入freemarker.jar
2.创建模本文件 myftl.ftl <html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome ${user}!</h1>
<p>点一下:
<a href="${websites.url}">${websites.name}</a>!
</body>
</html>
3.使用模板,生成新文件
Java代码 
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome ${user}!</h1>
<p>点一下:
<a href="${websites.url}">${websites.name}</a>!
</body>
</html>
- public class Make {
- public static void main(String[] args) {
- Configuration cfg = new Configuration();
- Template template = null;
- try {
- template = cfg.getTemplate("src/test/myftl.ftl");
- // cfg.setServletContextFromTemplateLoading(getServletContext,"WEB-INF/test.ftl");
- } catch (IOException e) {
- e.printStackTrace();
- }
- Map<String,Object> root = new HashMap<String,Object>();
- Map<String,Object> websites = new HashMap<String,Object>();
- root.put("user", "juju");
- root.put("websites", websites);
- websites.put("url", "http://www.google.com");
- websites.put("name", "谷歌");
- //输出到控制台
- //Writer w = new OutputStreamWriter(System.out);
- //输出到文件
- Writer w = null;
- try {
- w = new FileWriter("src/test/output.htm");
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- try {
- template.process(root, w);
- } catch (TemplateException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
本文介绍如何使用Freemarker模板引擎生成HTML页面。通过创建模板文件并使用Java代码加载数据,最终输出带有变量内容的新网页。
333

被折叠的 条评论
为什么被折叠?



