1.创建Web项目freeMarkerDemo。

2.添加jar包---freemarker-2.3.9.jar。

3.在WebContent目录下新建templates文件夹,用于放置模板文件ftl。

4.在templates目录下新建hello.ftl。

<html>
<head>
<title>Hello!</title>
</head>
<body>
<h1>hello ${user}!</h1>
</body>
</html>

5.在src目录下创建Hello.java文件。

package example;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map; public class Hello extends HttpServlet {
private Configuration cfg; public void init(){
cfg = new Configuration(); //设置FreeMarker的模版文件位置---此处的templates就是上面建的那个文件夹
cfg.setServletContextForTemplateLoading(getServletContext(),"templates");
} public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
//数据模型
Map root = new HashMap();
root.put("user", "xin"); //模版文件
Template temp =cfg.getTemplate("hello.ftl"); response.setContentType("text/html; charset=" + temp.getEncoding()); PrintWriter out = response.getWriter(); //模版+数据模型=输出
try{
temp.process(root,out);
}catch(TemplateException e){
e.printStackTrace();
}
} public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}

6.配置web.xml文件。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>freeMarkerDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>example.Hello</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/hello.do</url-pattern>
</servlet-mapping>
</web-app>

7.新建引导页面index.html。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head> <body>
点击下面链接看看效果:
<hr>
<a href="hello.do">调用Hello模板</a>
</body>
</html>

8.把项目部署到tomcate服务器,即可运行。

项目工作流程:首先看到index页面,发现程序跳转到hello.do;然后通过web.xml找到执行主体example.Hello,即Hello.java;执行该程序将数据user输出到模板文件hello.ftl中。

 

作为入门,我们来快速了解三个最为常见的指令---if,list,include

1.if指令

使用if指令可以有条件地跳过模板的一部分。

用法:<#if condition>…</#if>

使用<#else>标签可以指定当条件为假时程序执行的内容。

用法:<#if condition>…<#else>…</#if>

例子,修改hello.ftl

<html>
<head>
<title>Hello!</title>
</head>
<body>
<h1>
hello ${user}!
<#if user=="xin">
,my best friend!!!
<#else>
,happy new year!!!
</#if>
</h1>
</body>
</html>

2.list指令

当需要用列表来遍历集合的内容时,list指令是非常好用的。

list指令的一般格式为:

<#list sequence as loopVariable>repeatThis</#list>

repeatThis部分将会在给定的sequence遍历时在每项中重复,从第一项开始,一个接着一个。在所有的重复中,loopVariable将持有当前项的值。这个循环变量仅在于<#list …>和</#list>标签之间。

例子,假设有一组animals数据,如下:

  

java语句为:

List<Animal> animals = new ArrayList<Animal>();

Animal mouse = new Animal("mouse","small",50);
Animal elephant = new Animal("elephant","large",5000);
Animal python = new Animal("python","medium",4999); animals.add(mouse);
animals.add(elephant);
animals.add(python); Map<String, List<Animal>> root = new HashMap<String, List<Animal>>();
root.put("animals", animals);

其中Animal是自定义的一个实体类。

修改hello.ftl,以list的方式遍历animals列出所有的animal

<#list animals as being>
<h1>${being.name}---${being.size}---${being.price}</h1>
</#list>

3.include指令

使用include指令,可以在当前的模板中插入其他文件的内容。

用法:<#include “/a.html”>

在templates目录下新建文件a.html,内容为:

<hr>
<h3>Hello World~~~</h3>

当需要用到这个文件时,可以使用include指令来实现插入。

修改hello.ftl

<html>
<head>
<title>Hello!</title>
</head>
<body>
<h1>hello ${user}!</h1>
<#include "/a.html">
</body>
</html>

运行后将会在页面中显示出a.html中的内容。

 

上面的图显示的是一组以sequence序列存储的数据。

下面给出一组以hash表的形式存储的数据:

java语句为:

Map mouse = new HashMap();
mouse.put("size", "small");
mouse.put("price", 50); Animal elephant = new Animal("large",5000);
Animal python = new Animal("medium",4999); Map animals = new HashMap();
animals.put("mouse", mouse);
animals.put("elephant", elephant);
animals.put("python", python); Map<String, Object> root = new HashMap<String, Object>();
root.put("animals", animals);
root.put("test", "It is a test"); Map whatnot = new HashMap();
whatnot.put("because", "don't know");
root.put("whatnot", whatnot);

freeMarker入门示例的更多相关文章

  1. Freemarker 入门示例(zhuan)

    http://cuisuqiang.iteye.com/blog/2031768 ************************************ 初步学习freemarker ,先做一个简单 ...

  2. Freemarker 入门示例

    初步学习freemarker ,先做一个简单的HelloWord程序! 新建一个WEB工程,下载(我使用的是freemarker-2.3.20)freemarker并导入freemarker.jar, ...

  3. 1.【转】spring MVC入门示例(hello world demo)

    1. Spring MVC介绍 Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职责解耦,基于 ...

  4. 【转】spring MVC入门示例(hello world demo)

    部分内容来自网络:<第二章 Spring MVC入门 —— 跟开涛学SpringMVC > 1. Spring MVC介绍 Spring Web MVC是一种基于Java的实现了Web M ...

  5. [WCF编程]1.WCF入门示例

    一.WCF是什么? Windows Communication Foundation(WCF)是由微软开发的一系列支持数据通信的应用程序框架,整合了原有的windows通讯的 .net Remotin ...

  6. Maven入门示例(3):自动部署至外部Tomcat

    Maven入门示例(3):自动部署至外部Tomcat 博客分类:  maven 2012原创   Maven入门示例(3):自动部署至外部Tomcat 上一篇,介绍了如何创建Maven项目以及如何在内 ...

  7. 【java开发系列】—— spring简单入门示例

    1 JDK安装 2 Struts2简单入门示例 前言 作为入门级的记录帖,没有过多的技术含量,简单的搭建配置框架而已.这次讲到spring,这个应该是SSH中的重量级框架,它主要包含两个内容:控制反转 ...

  8. Spring MVC 入门示例讲解

    在本例中,我们将使用Spring MVC框架构建一个入门级web应用程序.Spring MVC 是Spring框架最重要的的模块之一.它以强大的Spring IoC容器为基础,并充分利用容器的特性来简 ...

  9. Couchbase之个人描述及入门示例

    本文不打算抄袭官方或者引用他人对Couchbase的各种描述,仅仅是自己对它的一点理解(错误之处,敬请指出),并附上一个入门示例. ASP.NET Web项目(其他web开发平台也一样)应用规模小的时 ...

随机推荐

  1. linux mount-umount命令常用记录

    每次挂在u盘都忘记,这次记录下. umount命令: 必杀:umount -l /dev/sda1 (有时候卸载不能卸,加-l(不是1,是小写字母l)参数,表示在设备不忙时卸载设备,就可成功卸载设备) ...

  2. 配置LANMP环境(2)-- 安装ifconfig命令与安装SecureCRT

    一.安装ifconfig命令 yum whatprovides ifconfig yum install net-tools 安装这个命令就是为了查看虚拟机的ip地址,SecureCRT连接必须要ip ...

  3. Consul实现原理系列文章1: 用Raft来实现分布式一致性

    工作中用到了Consul来做服务发现,之后一段时间里,我会陆续发一些文章来讲述Consul实现原理.在前一篇文章中,我介绍了Raft算法.这篇文章会讲讲Consul是如何使用Raft算法来实现分布式一 ...

  4. 结构体成员管理AVClass AVOption之1AVClass

    AVOption用于描述结构体中的成员变量.它最主要的作用可以概括为两个字:“赋值”. 一个AVOption结构体包含了变量名称,简短的帮助,取值等信息. 所有和AVOption有关的数据都存储在AV ...

  5. 面向对象JSON的继承(复制)与函数的继承(复制)

    今天这里和大家分享下如何复制对象 的属性 创建 对象的方式有三种,这里和大家分享下最常用的几种 1.JSON格式的方式创建对象 2.用函数的方式创建,然后用new关键字实例化对象,关于this的指向问 ...

  6. Python简单的线程池

    class ThreadPool(object): def __init__(self, max_num=20): # 创建一个队列,队列里最多只能有10个数据 self.queue = queue. ...

  7. 构造方法与构造块的执行顺序(区别于static)

    小面试题:在类的实例化时,会调用类的构造块(类中的构造块)和构造方法,无论构造方法在前还是在后,都先执行构造块 class Person{ public Person(){ System.out.pr ...

  8. java中InputStream转化为byte[]数组

    //org.apache.commons.io.IOUtils.toByteArray已经有实现 String filePath = "D:\\aaa.txt"; in = new ...

  9. jmGraph:一个基于html5的简单画图组件

    jmGraph:一个基于html5的简单画图组件 特性: 代码书写简单易理解 面向对象的代码结构 对图形控件化 样式抽离 模块化:入seajs实现模块化开发 兼容性:暂只推荐支持html5的浏览器:i ...

  10. LIS(模板)

    记录一下,O(nlgn)的算法求LIS //HHH #include <iostream> #include <stdio.h> #include <string.h&g ...