freemark

来源:互联网 发布:帝国cms模板安装教程 编辑:程序博客网 时间:2024/05/16 18:30

导入JAR包

需要导入以下JAR包
1. freemarker-2.3.19.jar
2. junit.jar
3. org.hamcrest.core_1.3.0.v201303031735.jar

使用freemarker需用到freemarker-2.3.19.jar,测试使用junit.jar,junit.jar依赖于org.hamcrest.core_1.3.0.v201303031735.jar。jar包下载可点击这里下载

创建项目

创建项目,结构如下:
项目结构

创建FreemarkerUtil类

package com.ljq.fm;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.io.PrintWriter;import java.util.Map;import freemarker.template.Configuration;import freemarker.template.Template;import freemarker.template.TemplateException;public class FreemarkerUtil {    public Template getTemplate(String name) {        try {            // 通过Freemaker的Configuration读取相应的ftl            Configuration cfg = new Configuration();            // 设定去哪里读取相应的ftl模板文件            cfg.setClassForTemplateLoading(this.getClass(), "/ftl");            // 在模板文件目录中找到名称为name的文件            Template temp = cfg.getTemplate(name);            return temp;        } catch (IOException e) {            e.printStackTrace();        }        return null;    }    /**     * 控制台输出     *      * @param name     * @param root     */    public void print(String name, Map<String, Object> root) {        try {            // 通过Template可以将模板文件输出到相应的流            Template temp = this.getTemplate(name);            temp.process(root, new PrintWriter(System.out));        } catch (TemplateException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }    /**     * 输出HTML文件     *      * @param name     * @param root     * @param outFile     */    public void fprint(String name, Map<String, Object> root, String outFile) {        FileWriter out = null;        try {            // 通过一个文件输出流,就可以写到相应的文件中,此处用的是绝对路径            out = new FileWriter(new File("E:/workspace/freemarkprj/page/" + outFile));            Template temp = this.getTemplate(name);            temp.process(root, out);        } catch (IOException e) {            e.printStackTrace();        } catch (TemplateException e) {            e.printStackTrace();        } finally {            try {                if (out != null)                    out.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }}

创建Group类

package com.ljq.fm;/** *  *  * @author 林计钦 * @version 1.0 2013-10-25 下午02:36:09 */public class Group {    private String name;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}

创建User类

package com.ljq.fm;import java.io.Serializable;@SuppressWarnings("serial")public class User implements Serializable {    private int id;    private String name;    private int age;    private Group group;    public Group getGroup() {        return group;    }    public void setGroup(Group group) {        this.group = group;    }    public User() {    }    public User(int id, String name, int age) {        this.id = id;        this.name = name;        this.age = age;    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }}

创建01.ftl

<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>测试</title></head><body><h1>你好${username}</h1></body></html>

创建02.ftl

<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><h1>你好: ${username}</h1></body></html>

创建03.ftl

<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><h1>${user.id}-----${user.name}-----${user.age}</h1><#if user.age lt 12>    ${user.name}还是一个小孩<#elseif user.age lt 18>    ${user.name}快成年<#else>    ${user.name}已经成年</#if></body></html>

创建04.ftl

<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><#list users as user>${user.id}---------${user.name}-------${user.age}<br/></#list></body></html>

创建05.ftl

<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><hr/><#list users as user>${user.id}---------${user.name}-------${user.age}<br/></#list></body></html>

创建06.ftl

<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body>${user.id}-------${user.name}------${user.group!}  <#-- !后为空就不输出  --><#--${user.group.name!}--><#-- 按照以上的方式加! freemarker仅仅只会判断group.name是不是空值 -->${(user.group.name)!"1234"} ${(a.b)!"没有a.b元素"}<#--!:指定缺失变量的默认值 ??:判断某个变量是否存在,返回boolean--><#if (a.b)??> <#--if后不用加$-->    不为空<#else>    为空</#if></body></html>

创建FreemarkerTest测试类

package com.ljq.fm;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.junit.Test;public class FreemarkerTest {    @Test    public void test(){        FreemarkerUtil util = new FreemarkerUtil();        Map<String, Object> map = new HashMap<String, Object>();        Group group = new Group();        group.setName("IT");        User user = new User();        user.setId(001);        user.setName("张三");        user.setAge(12);        user.setGroup(group);        List<User> users = new ArrayList<User>();        users.add(user);        users.add(user);        users.add(user);        map.put("user", user);        //普通EL赋值        //util.print("01.ftl", map );        //判断        //util.print("03.ftl", map, "03.html");        //遍历        //util.print("05.ftl", map);        //子元素判断        util.print("06.ftl", map);    }}

创建ClassUtil类

创建此类的原因是自己想根据实体类的字段用freemarker缩短工作时间,提高工作效率,但暂时还没和freemarker关联起来,后续有时间再续集

package com.ljq.fm;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.Date;public class ClassUtil {    /**      * 遍历实体类的属性和数据类型以及属性值      * @param model      * @throws NoSuchMethodException      * @throws IllegalAccessException      * @throws IllegalArgumentException      * @throws InvocationTargetException      */      public static void reflectTest(Object model) throws NoSuchMethodException,                      IllegalAccessException, IllegalArgumentException,                      InvocationTargetException {          // 获取实体类的所有属性,返回Field数组          Field[] field = model.getClass().getDeclaredFields();          // 遍历所有属性          for (int j = 0; j < field.length; j++) {                  // 获取属性的名字                  String name = field[j].getName();                  // 将属性的首字符大写,方便构造get,set方法                  name = name.substring(0, 1).toUpperCase() + name.substring(1);                  // 获取属性的类型                  String type = field[j].getGenericType().toString();                  // 如果type是类类型,则前面包含"class ",后面跟类名                  System.out.println("属性为:" + name);                  if (type.equals("class java.lang.String")) {                          Method m = model.getClass().getMethod("get" + name);                          // 调用getter方法获取属性值                          String value = (String) m.invoke(model);                          System.out.println("数据类型为:String");                          if (value != null) {                                  System.out.println("属性值为:" + value);                          } else {                                  System.out.println("属性值为:空");                          }                  }                  if (type.equals("class java.lang.Integer")) {                          Method m = model.getClass().getMethod("get" + name);                          Integer value = (Integer) m.invoke(model);                          System.out.println("数据类型为:Integer");                          if (value != null) {                                  System.out.println("属性值为:" + value);                          } else {                                  System.out.println("属性值为:空");                          }                  }                  if (type.equals("class java.lang.Short")) {                          Method m = model.getClass().getMethod("get" + name);                          Short value = (Short) m.invoke(model);                          System.out.println("数据类型为:Short");                          if (value != null) {                                  System.out.println("属性值为:" + value);                          } else {                                  System.out.println("属性值为:空");                          }                  }                  if (type.equals("class java.lang.Double")) {                          Method m = model.getClass().getMethod("get" + name);                          Double value = (Double) m.invoke(model);                          System.out.println("数据类型为:Double");                          if (value != null) {                                  System.out.println("属性值为:" + value);                          } else {                                  System.out.println("属性值为:空");                          }                  }                  if (type.equals("class java.lang.Boolean")) {                          Method m = model.getClass().getMethod("get" + name);                          Boolean value = (Boolean) m.invoke(model);                          System.out.println("数据类型为:Boolean");                          if (value != null) {                                  System.out.println("属性值为:" + value);                          } else {                                  System.out.println("属性值为:空");                          }                  }                  if (type.equals("class java.util.Date")) {                          Method m = model.getClass().getMethod("get" + name);                          Date value = (Date) m.invoke(model);                          System.out.println("数据类型为:Date");                          if (value != null) {                                  System.out.println("属性值为:" + value);                          } else {                                  System.out.println("属性值为:空");                          }                  }                  if (type.equals("double")) {                      Method m = model.getClass().getMethod("get" + name);                      double value = (double) m.invoke(model);                      System.out.println("数据类型为:double");                      if (value >0) {                              System.out.println("属性值为:" + value);                      } else {                              System.out.println("属性值为:空");                      }                  }                  if (type.equals("int")) {                      Method m = model.getClass().getMethod("get" + name);                      int value = (int) m.invoke(model);                      System.out.println("数据类型为:int");                      if (value >0) {                              System.out.println("属性值为:" + value);                      } else {                              System.out.println("属性值为:空");                      }                  }          }      }      public static void main(String[] args) {        try {            ClassUtil.reflectTest(new User());        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}

后记:我用MyEclipse创建项目时后,执行到以下位置时老报找不到ftl文件。

cfg.setClassForTemplateLoading(this.getClass(), "/ftl");

后来我改成下面这样就可以了。

cfg.setClassForTemplateLoading(this.getClass(), "../ftl");
0 0
原创粉丝点击