第一讲 Hello FreeMarker

来源:互联网 发布:淘宝分销和代销的区别 编辑:程序博客网 时间:2024/05/29 18:39
一、导入jar包

           <dependency>
                <groupId>org.freemarker</groupId>
                <artifactId>freemarker</artifactId>
                <version>2.3.23</version>
           </dependency>

二、FreeMarker案例

  1. 编写模板(index.ftl):

<!DOCTYPEhtml>
<html>
<head>
<metacharset="UTF-8">
<title>我的FreeMarker页面</title>
</head>
<body>
${name}
</body>
</html>

   就是新建一个html页面,然后将后缀名改为ftl

  1. 编写测试类:

publicclassHello {
     
     publicstaticvoidmain(String[]args)throwsIOException, TemplateException {
           //Configuration用来读取模板文件
           Configurationcfg=newConfiguration(Configuration.VERSION_2_3_23);
           
           //设置freemarker模板的加载目录
           cfg.setDirectoryForTemplateLoading(newFile("src/main/resources"));
           //根据模板名获得模板
           Templatetemplate=cfg.getTemplate("index.ftl");
           //要显示的数据
           Map<String, String>map=newHashMap<String, String>();
           map.put("name","小薇");
           //根据模板创建静态页面
           Writerwriter=newFileWriter(newFile("src/main/resources/hello.html"));
           template.process(map,writer);
           writer.flush();
           writer.close();
           
           //测试路径
           //F:\
           System.out.println(newFile("/").getAbsolutePath());
           //F:\Java\JavaEE\workspace\freemarker\.
           System.out.println(newFile("./").getAbsolutePath());
           System.out.println("Hello");
     }
     
}

   new File("src/main/resources/hello.html"),只是用来获得文件路径,实际上并没有创建文件。

  1. 测试结果:

   发现在src/main/resources/路径下多了一个hello.html的静态页面。且模板index.ftl${name}也显示为小薇

<!DOCTYPEhtml>
<html>
<head>
<metacharset="UTF-8">
<title>我的FreeMarker页面</title>
</head>
<body>
小薇
</body>
</html>




原创粉丝点击