初始化(1)

官网地址

经久不衰的优秀模板框架,对于固定的的静态页面都可以使用

初始化使用

  1. 引入jar包(推荐使用最新版)
<dependency>
   <groupId>org.freemarker</groupId>
   <artifactId>freemarker</artifactId>
   <version>2.3.19</version>
</dependency>

2 创建使用类

public class FreemarkerUtil {
   private static Configuration cfg;
   public FreemarkerUtil() {
      initFreemarker();
   }
   private void initFreemarker() {
      cfg = new Configuration();
      cfg.setClassForTemplateLoading(this.getClass(), "/");
      cfg.setDefaultEncoding("UTF-8");
   }
  }

3 加载模板文件处理数据

    //获取模板路径,后缀一般为ftl
	Template template = cfg.getTemplate("ftl/"+ ftlName +".ftl");
     Writer out= new OutputStreamWriter(new FileOutputStream(accountPath) , "UTF-8");
     template.process(obj, out);}
	 //处理后数据 记得关闭流
	 //  out.flush();
     // out.close();   

4 完整例子

 FreemarkerUtil f  = new FreemarkerUtil();
        Configuration cfg = new Configuration();
        cfg.setClassForTemplateLoading(f.getClass(),"/");
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

        /* Create a data-model */
        Map root = new HashMap();
        root.put("user", "Big Joe");
        Product latest = new Product();
        latest.setUrl("products/greenmouse.html");
        latest.setName("green mouse");
        root.put("latestProduct", latest);
        /* Get the template (uses cache internally) */
        Template temp = cfg.getTemplate("ftl/template.ftl");

        /* Merge data-model with template */
        Writer out = new OutputStreamWriter(System.out);
        temp.process(root, out);

1.创建HTML模版

   <html>
<head>
    <title>Welcome!</title>
</head>
<body>
<h1>Welcome ${user}!</h1>
<p>Our latest product:
    <a href="${latestProduct.url}">${latestProduct.name}</a>!
</body>
</html>

2.创建实体类

@Data
public class Product {
    String url;
    String name;
}
使用此注解配合lombok一起使用

3.运行main方法输出到控制台

<html>
<head>
    <title>Welcome!</title>
</head>
<body>
<h1>Welcome Big Joe!</h1>
<p>Our latest product:
    <a href="products/greenmouse.html">green mouse</a>!
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值