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. java 无状态和有状态区别

     诸位Java程序员,想必大家对SimpleDateFormat并不陌生.不过,你是否知道,SimpleDateFormat不是线程安全的(thread safe).这意味着,下面的代码是错误的: ...

  2. (初学者)安装hadoop集群注意事项

    1.关闭防火墙 2.所有的hadoop操作都是hadoop用户下面的,同时需要用hadoop用户登录之后,对于其他的机器的hadoop用户可以免密登录 3.hadoop用户在root组下面,不是附加组 ...

  3. 我的第三个java程序 两数相加

    import java.util.Scanner; public class Test { public static void main(String [] args) { Scanner sc = ...

  4. 支付宝热补丁技术— AndFix原理[阿里Hao]

    本文由嵌入式企鹅圈原创团队成员.阿里资深project师Hao分享. 上次我们介绍了用dexposed方案实施热补丁的原理.它本质上就是hook要改动的函数.这样一来在正式版本号公布时就不能直接拿热补 ...

  5. TensorFlow实战:Chapter-4(CNN-2-经典卷积神经网络(AlexNet、VGGNet))

    转载自:http://blog.csdn.net/u011974639/article/details/76146822 项目:https://www.cs.toronto.edu/~frossard ...

  6. lumen 获得当前uri 如/xxx/{id}

    因为想实现通过url判断是否有权限,所有需要拿到当前的route方法的name,如下 $api->get('role/grant/{id}', 'RoleController@getGrant' ...

  7. redis字典的底层实现hashTable

    Redis的字典使用哈希表作为底层实现.一个哈希表里面可以有多个哈希表节点,而每个哈希表节点就保存了字典中的一个键值对 哈希表的数据结构为 table属性是一个数组,数组中的每个元素都是指向dictE ...

  8. [Spring Data MongoDB]学习笔记--MongoTemplate查询操作

    查询操作主要用到两个类:Query, Criteria 所有的find方法都需要一个query的object. 1. 直接通过json来查找,不过这种方式在代码中是不推荐的. BasicQuery q ...

  9. window.XMLHttpRequest对象详解

    来自:http://blog.csdn.net/lccone/article/details/7743946 window.XMLHttpRequest XMLHttpRequest对象是当今所有AJ ...

  10. 巨蟒python全栈开发django5:组件&&CBV&FBV&&装饰器&&ORM增删改查

    内容回顾: 补充反向解析 Html:{% url ‘别名’ 参数 %} Views:reverse(‘别名’,args=(参数,)) 模板渲染 变量 {{ 变量名 }} 逻辑相关 {% %} 过滤器: ...