Freemarker入门案例

首先需要到freemarker官方下载freemarker的jar包,导入到项目中,如:freemarker-2.3.19.jar

1、先建个freemarker的工具类,FreemarkerUtil.java

  1. package com.ljq.fm;
  2.  
  3. import java.io.File;
  4. import java.io.FileWriter;
  5. import java.io.IOException;
  6. import java.io.PrintWriter;
  7. import java.util.Map;
  8.  
  9. import freemarker.template.Configuration;
  10. import freemarker.template.Template;
  11. import freemarker.template.TemplateException;
  12.  
  13. public class FreemarkerUtil {
  14.  
  15. public Template getTemplate(String name) {
  16. try {
  17. // 通过Freemaker的Configuration读取相应的ftl
  18. Configuration cfg = new Configuration();
  19. // 设定去哪里读取相应的ftl模板文件
  20. cfg.setClassForTemplateLoading(this.getClass(), "/ftl");
  21. // 在模板文件目录中找到名称为name的文件
  22. Template temp = cfg.getTemplate(name);
  23. return temp;
  24. } catch (IOException e) {
  25. e.printStackTrace();
  26. }
  27. return null;
  28. }
  29.  
  30. /**
  31. * 控制台输出
  32. *
  33. * @param name
  34. * @param root
  35. */
  36. public void print(String name, Map<String, Object> root) {
  37. try {
  38. // 通过Template可以将模板文件输出到相应的流
  39. Template temp = this.getTemplate(name);
  40. temp.process(root, new PrintWriter(System.out));
  41. } catch (TemplateException e) {
  42. e.printStackTrace();
  43. } catch (IOException e) {
  44. e.printStackTrace();
  45. }
  46. }
  47.  
  48. /**
  49. * 输出HTML文件
  50. *
  51. * @param name
  52. * @param root
  53. * @param outFile
  54. */
  55. public void fprint(String name, Map<String, Object> root, String outFile) {
  56. FileWriter out = null;
  57. try {
  58. // 通过一个文件输出流,就可以写到相应的文件中,此处用的是绝对路径
  59. out = new FileWriter(new File("E:/workspace/freemarkprj/page/" + outFile));
  60. Template temp = this.getTemplate(name);
  61. temp.process(root, out);
  62. } catch (IOException e) {
  63. e.printStackTrace();
  64. } catch (TemplateException e) {
  65. e.printStackTrace();
  66. } finally {
  67. try {
  68. if (out != null)
  69. out.close();
  70. } catch (IOException e) {
  71. e.printStackTrace();
  72. }
  73. }
  74. }
  75. }

2 、在src目录下建个ftl包,用于存放ftl模板文件,this.getClass() 就是根据当前类的路径获取模板文件位置
01.ftl

  1. <html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  4. <title>测试</title>
  5. </head>
  6.  
  7. <body>
  8. <h1>你好${username}</h1>
  9. </body>
  10. </html>

02.ftl

  1. <html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  4. <title>Insert title here</title>
  5. </head>
  6.  
  7. <body>
  8. <h1>你好: ${username}</h1>
  9. </body>
  10. </html>

03.ftl

  1. <html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  4. <title>Insert title here</title>
  5. </head>
  6. <body>
  7. <h1>${user.id}-----${user.name}-----${user.age}</h1>
  8. <#if user.age lt 12>
  9. ${user.name}还是一个小孩
  10. <#elseif user.age lt 18>
  11. ${user.name}快成年
  12. <#else>
  13. ${user.name}已经成年
  14. </#if>
  15. </body>
  16. </html>

04.ftl

  1. <html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  4. <title>Insert title here</title>
  5. </head>
  6. <body>
  7. <#list users as user>
  8. ${user.id}---------${user.name}-------${user.age}<br/>
  9. </#list>
  10. </body>
  11. </html>

05.ftl

  1. <html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  4. <title>Insert title here</title>
  5. </head>
  6.  
  7. <body>
  8. <hr/>
  9. <#list users as user>
  10. ${user.id}---------${user.name}-------${user.age}<br/>
  11. </#list>
  12. </body>
  13. </html>

06.ftl

  1. <html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  4. <title>Insert title here</title>
  5. </head>
  6.  
  7. <body>
  8. ${user.id}-------${user.name}------${user.group!} <#-- !后为空就不输出 -->
  9. <#--${user.group.name!}--><#-- 按照以上的方式加! freemarker仅仅只会判断group.name是不是空值 -->
  10. ${(user.group.name)!"1234"}
  11.  
  12. ${(a.b)!"没有a.b元素"}
  13.  
  14. <#--
  15. !:指定缺失变量的默认值
  16. ??:判断某个变量是否存在,返回boolean值
  17. -->
  18. <#if (a.b)??> <#--if后不用加$-->
  19. 不为空
  20. <#else>
  21. 为空
  22. </#if>
  23. </body>
  24. </html>

实体类User.java

  1. package com.ljq.fm;
  2.  
  3. import java.io.Serializable;
  4.  
  5. @SuppressWarnings("serial")
  6. public class User implements Serializable {
  7. private int id;
  8. private String name;
  9. private int age;
  10. private Group group;
  11.  
  12. public Group getGroup() {
  13. return group;
  14. }
  15.  
  16. public void setGroup(Group group) {
  17. this.group = group;
  18. }
  19.  
  20. public User() {
  21. }
  22.  
  23. public User(int id, String name, int age) {
  24. this.id = id;
  25. this.name = name;
  26. this.age = age;
  27. }
  28.  
  29. public int getId() {
  30. return id;
  31. }
  32.  
  33. public void setId(int id) {
  34. this.id = id;
  35. }
  36.  
  37. public String getName() {
  38. return name;
  39. }
  40.  
  41. public void setName(String name) {
  42. this.name = name;
  43. }
  44.  
  45. public int getAge() {
  46. return age;
  47. }
  48.  
  49. public void setAge(int age) {
  50. this.age = age;
  51. }
  52.  
  53. }

实体类Group.java

  1. package com.ljq.fm;
  2.  
  3. /**
  4. *
  5. *
  6. * @author 林计钦
  7. * @version 1.0 2013-10-25 下午02:36:09
  8. */
  9. public class Group {
  10. private String name;
  11.  
  12. public String getName() {
  13. return name;
  14. }
  15.  
  16. public void setName(String name) {
  17. this.name = name;
  18. }
  19.  
  20. }

3、再建个Junit的测试类 FreemarkerTest.java

  1. package com.ljq.fm;
  2.  
  3. import java.io.File;
  4. import java.io.FileWriter;
  5. import java.io.IOException;
  6. import java.io.PrintWriter;
  7. import java.util.Map;
  8.  
  9. import freemarker.template.Configuration;
  10. import freemarker.template.Template;
  11. import freemarker.template.TemplateException;
  12.  
  13. public class FreemarkerUtil {
  14.  
  15. public Template getTemplate(String name) {
  16. try {
  17. // 通过Freemaker的Configuration读取相应的ftl
  18. Configuration cfg = new Configuration();
  19. // 设定去哪里读取相应的ftl模板文件
  20. cfg.setClassForTemplateLoading(this.getClass(), "/ftl");
  21. // 在模板文件目录中找到名称为name的文件
  22. Template temp = cfg.getTemplate(name);
  23. return temp;
  24. } catch (IOException e) {
  25. e.printStackTrace();
  26. }
  27. return null;
  28. }
  29.  
  30. /**
  31. * 控制台输出
  32. *
  33. * @param name
  34. * @param root
  35. */
  36. public void print(String name, Map<String, Object> root) {
  37. try {
  38. // 通过Template可以将模板文件输出到相应的流
  39. Template temp = this.getTemplate(name);
  40. temp.process(root, new PrintWriter(System.out));
  41. } catch (TemplateException e) {
  42. e.printStackTrace();
  43. } catch (IOException e) {
  44. e.printStackTrace();
  45. }
  46. }
  47.  
  48. /**
  49. * 输出HTML文件
  50. *
  51. * @param name
  52. * @param root
  53. * @param outFile
  54. */
  55. public void fprint(String name, Map<String, Object> root, String outFile) {
  56. FileWriter out = null;
  57. try {
  58. // 通过一个文件输出流,就可以写到相应的文件中,此处用的是绝对路径
  59. out = new FileWriter(new File("E:/workspace/freemarkprj/page/" + outFile));
  60. Template temp = this.getTemplate(name);
  61. temp.process(root, out);
  62. } catch (IOException e) {
  63. e.printStackTrace();
  64. } catch (TemplateException e) {
  65. e.printStackTrace();
  66. } finally {
  67. try {
  68. if (out != null)
  69. out.close();
  70. } catch (IOException e) {
  71. e.printStackTrace();
  72. }
  73. }
  74. }
  75. }

Freemarker入门案例的更多相关文章

  1. SpringBoot快速入门(解析+入门案例源码实现)

    这里写目录标题 SpringBoot入门 一.SpringBoot 概念 二.JavaConfig 入门 1. JavaConfig 概念 2. 项目准备 三.常用注解 四.SpringBoot 入门 ...

  2. SpringMVC入门案例及请求流程图(关于处理器或视图解析器或处理器映射器等的初步配置)

    SpringMVC简介:SpringMVC也叫Spring Web mvc,属于表现层的框架.Spring MVC是Spring框架的一部分,是在Spring3.0后发布的 Spring结构图 Spr ...

  3. SpringMvc核心流程以及入门案例的搭建

    1.什么是SpringMvc Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面.Spring 框架提供了构建 Web 应用程序的全功能 M ...

  4. Struts2第一个入门案例

      一.如何获取Struts2,以及Struts2资源包的目录结构的了解    Struts的官方地址为http://struts.apache.org 在他的主页当中,我们可以通过左侧的Apache ...

  5. MyBatis入门案例、增删改查

    一.MyBatis入门案例: ①:引入jar包 ②:创建实体类 Dept,并进行封装 ③ 在Src下创建大配置mybatis-config.xml <?xml version="1.0 ...

  6. Hibernate入门案例及增删改查

    一.Hibernate入门案例剖析: ①创建实体类Student 并重写toString方法 public class Student { private Integer sid; private I ...

  7. Quartz应用实践入门案例二(基于java工程)

    在web应用程序中添加定时任务,Quartz的简单介绍可以参看博文<Quartz应用实践入门案例一(基于Web应用)> .其实一旦学会了如何应用开源框架就应该很容易将这中框架应用与自己的任 ...

  8. Quartz应用实践入门案例一(基于Web环境)

    Quartz是一个完全由java编写的开源作业调度框架,正是因为这个框架整合了许多额外的功能,所以在使用上就显得相当容易.只是需要简单的配置一下就能轻松的使用任务调度了.在Quartz中,真正执行的j ...

  9. MyBatis入门案例 增删改查

    一.MyBatis入门案例: ①:引入jar包 ②:创建实体类 Dept,并进行封装 ③ 在Src下创建大配置mybatis-config.xml <?xml version="1.0 ...

随机推荐

  1. java 继承与多态

    Example5_11.java class 动物 { void cry() { } } class 狗 extends 动物 { void cry() { System.out.println(&q ...

  2. mplayer最全的命令

    前段时间做过qt内嵌mplayer的一个小程序,感觉mplayer还行不过不支持打开图片感觉有点无力.话不多说上代码: QString path="d:/1.mkv"; QWidg ...

  3. 5--OC--构造方法

    //  Created by Stephen on 16/3/2.//  Copyright © 2016年 Stephen. All rights reserved.//// 回顾上一章节Perso ...

  4. maven认识

    在这里普及一下知识: ┣ maven与ant是同类,构建工具 ┣ svn与cvs,css是同类,版本控制工具 1.为什么要用Maven? 在进行软件开发的过程中,无论什么项目,采用何种技术,使用何种编 ...

  5. CodeForces 670 A. Holidays(模拟)

    Description On the planet Mars a year lasts exactly n days (there are no leap years on Mars). But Ma ...

  6. ubuntu上的mysql数据库双机备份设置

    配置环境: myslq 5.5.3 + ubuntu server 12.04 一.配置MySQL主服务器(192.168.0.1) 1.增加一个账号专门用于同步 1 mysql>grant r ...

  7. spring项目中的定时任务实现和问题解决

    之前我用JAVA中的Timer类实现了服务器的定时任务,具体详见之前的博文. 后来发现了一个更简单的实现方式,利用spring中的@Scheduled注解实现觉得简单的很多. 确实spring封装的特 ...

  8. ignite学习笔记

    1.一个Ignite节点可以从命令行启动,可以用默认的配置也可以传递一个配置文件.可以启动很多很多的节点然后他们会自动地发现对方. 2.Ignite只需要一个ignite-core强依赖,通常你还需要 ...

  9. Puzzles

    Puzzles Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 thr ...

  10. 文件夹添加 IIS 应用程序池用户权限

    http://serverfault.com/questions/81165/how-to-assign-permissions-to-applicationpoolidentity-account ...