一、最原始示例

1、引入POM依赖

        <!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.26-incubating</version>
</dependency> <!-- Servlet Library -->
<!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>

2、在WEB-INF/ftl中建立test.ftl

<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>
Welcome ${user}<#if user == "Big Joe">, our beloved leader</#if>!
</h1>
</body>
</html>

3、添加TestServlet.java

package com.jsoft.testfreemarker;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import freemarker.template.Configuration;
import freemarker.template.Template; /**
* Servlet implementation class TestServlet
*/
@WebServlet(name = "test", urlPatterns = "/test")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L; private Configuration cfg; @Override
public void init() throws ServletException {
// initialize operation
cfg = new Configuration(Configuration.VERSION_2_3_26);
cfg.setServletContextForTemplateLoading(getServletContext(), "WEB-INF/ftl");
}
/**
* Default constructor.
*/
public TestServlet() {
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
Map<String, Object> data = new HashMap<String, Object>();
data.put("user", "Big Joe");
// 得到模板
try {
// 将模板和数据结合,并返回浏览器
Template template = cfg.getTemplate("test.ftl");
template.process(data, response.getWriter());
} catch (Exception e) {
// e.printStackTrace();
response.getWriter().print("暂时无数据"
);
}

} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }

提示:采用了Servlet3.x的注解功能,不需要在web.xml中再配置映射。

4、测试效果

测试工程:https://github.com/easonjim/5_java_example/tree/master/freemarker/test2

二、高级一点的集成

1、在web.xml引入FreeMarker提供的Servlet

    <servlet>
<servlet-name>freemarker</servlet-name>
<servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>
<init-param>
<param-name>TemplatePath</param-name>
<param-value>/</param-value>
</init-param>
<init-param>
<param-name>NoCache</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>ContentType</param-name>
<param-value>text/html;charset=UTF-8</param-value>
</init-param>
<init-param>
<param-name>template_update_delay</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>default_encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>number_format</param-name>
<param-value>0.##########</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>freemarker</servlet-name>
<url-pattern>*.ftl</url-pattern>
</servlet-mapping>

2、新建test.ftl模板文件

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN" dir="ltr">
<head>
<title>test!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div>
直接显示字符串<br />
String:${strValue}<br/>
<hr/>
</div> <div>
显示日期
date:${myDate?date}<br/>
<hr/>
显示时间
time:${myDate?time}<br/>
<hr/>
显示时间戳
datetime:${myDate?datetime}<br/>
<hr/>
</div> <div>
访问对象数组
ObjectArray:
${objectArray[0]},${objectArray[1]},${objectArray[2]}
<br />
<hr/>
</div> <div>
遍历Set中的元素
SetData:<br />
<#list setData as value>
${value}
</#list>
<hr/>
</div> <div>
遍历List中的元素
strList:<br/>
<#list strList as strValue >
<#if strValue_index == >
${strValue} is first element
<#elseif !strValue_has_next>
${strValue} is last element
<#else>
${strValue}
</#if>
<br />
</#list>
<hr/>
</div> <div>
获取map中的值
<br/>
map:
key1=${map.key1},key2=${map.key2},key3=${map.key3}
<hr/>
</div> <#include "foot.html">
</body>
</html>

foot.html为了演示模板中引入文件的效果

<div style="margin-top: 50px;text-align: center;font-size: 12px">
<hr />
this is foot
</div>

3、编写Servlet,这次的Servlet完全不用涉及到FreeMarker的类库使用,只关心Model即可。

package com.jsoft.testfreemarker;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class TestServlet
*/
@WebServlet(name = "test", urlPatterns = "/test")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* Default constructor.
*/
public TestServlet() {
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String strValue = "this is String";
Date myDate = new Date();
Object[] objectArray = new Object[] { 1, "str", 1.2 }; Set<Object> setData = new HashSet<Object>();
setData.add("dataValue1");
setData.add("dataValue2");
setData.add("dataValue3"); List<String> strList = new ArrayList<String>();
strList.add("字符串1");
strList.add("字符串2");
strList.add("字符串3"); Map<String, Object> map = new HashMap<String, Object>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3"); request.setAttribute("strValue", strValue);
request.setAttribute("objectArray", objectArray);
request.setAttribute("strList", strList);
request.setAttribute("map", map);
request.setAttribute("myDate", myDate);
request.setAttribute("setData", setData);
request.getRequestDispatcher("/WEB-INF/ftl/test.ftl"
).forward(request, response);
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }

4、测试效果

测试工程:https://github.com/easonjim/5_java_example/tree/master/freemarker/test3

FreeMarker与Servlet结合示例的更多相关文章

  1. Freemarker与Servlet

    1.导入jar包(freemarker.jar) 2.web.xml配置一个普通servlet <servlet> <servlet-name>hello</servle ...

  2. Servlet小示例:jsp页面提交信息Servlet接收并打印输出

    该示例采用doPost方法提交表单,该示例一共包含两个文件. 一个是用来提交用户信息的表单userForm2.jsp,另一个是用来接收参数的Servlet. userForm2.jsp <%@ ...

  3. Servlet Filter 示例

    1. CityQuery.java package com.xxx.servlet; import com.google.common.collect.Lists; import com.xxx.da ...

  4. 开发一个Servlet示例

    Servlet响应请求步骤: Servlet是一个基于Java技术的Web组件,运行在服务器端,用户利用Servlet可以很轻松地扩展Web服务器的功能,使其满足特定的应用需要.Tomcat是一个常用 ...

  5. freemarker学习 (servlet + freemarker -> Struts2+freemarker -> springMVC+freemarker)

    什么是freemarker? freemarker类似于jsp,但不是jsp!怎么说呢?freemarker文件后缀是.ftl,它不像jsp本质是servlet,它将构建模板.解析模板.使用模板分离开 ...

  6. 【学习笔记】FreeMarker 之于Servlet与Stuts2的应用

    FreeMarker应用在Servlet(0配置web.xml形式): 准备环境: tomcat7.eclipse最新版.jdk1.8.freemarker v2.3.20.jar 举例项目结构图: ...

  7. FreeMarker的基础语法

    FreeMarker语言 FreeMarker语言概述 FreeMarker是一个模板引擎,一个基于模板生成文本输出的通用工具,使用纯Java编写. FreeMarker被设计用来生成HTML Web ...

  8. Spring MVC 学习总结(七)——FreeMarker模板引擎与动态页面静态化

    模板引擎可以让程序实现界面与数据分离,业务代码与逻辑代码的分离,这就提升了开发效率,良好的设计也使得代码复用变得更加容易.一般的模板引擎都包含一个模板解析器和一套标记语言,好的模板引擎有简洁的语法规则 ...

  9. 用freemarker生产静态页面

    FreeMarker概述 * FreeMarker是一个模板引擎,一个基于模板生成文本输出的通用工具,使用纯Java编写     * Template + data model = output    ...

随机推荐

  1. Linux命令(007) -- systemctl

    systemctl命令是系统服务管理指令,它实际上是将service和chkconfig两个命令组合到一起. 任务 旧指令 新指令 使某服务自动启动 chkconfig --level 3 httpd ...

  2. web项目无法部署到eclipse配置的本地tomcat

    一.发现问题 在eclipse中新建Dynamic Web Project,配置好本地的tomcat并写好代码后选择Run on Server,但运行后发现在tomcat的安装目录下的webapps并 ...

  3. Intellij使用心得(四) -- 导入Eclipse的代码格式化文件

    https://my.oschina.net/flashsword/blog/137598

  4. Java 遍历Map对象的4种方法

    http://blog.csdn.net/tjcyjd/article/details/11111401

  5. responsive-navigator

    html 代码: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> < ...

  6. javascirpt中的数字在计算机内存储为多少Byte

    JavaScript内部,所有数字都是以64位浮点数形式储存,即使整数也是如此 8 Byte = 64bit Javascript中,由于其变量内容不同,变量被分为基本数据类型变量和引用数据类型变量. ...

  7. opencv识别验证码的教程和资料

    简书教程:https://www.jianshu.com/p/41127bf90ca9 博客园教程(较详细):https://www.cnblogs.com/qqandfqr/p/7866650.ht ...

  8. 面试中的一些小问题之html5和html4的区别?

    HTML5建立的一些新规则: 新特性应该基于HTML.CSS.DOM.JavaScript: 减少对外部插件的需求,如flash将会用video标签和audio标签代替: 更加优秀的错误处理: 更多取 ...

  9. Reuse a SSL socket

    It's possible to reuse a SSL socket after proper cleanup. See SSL Socket free and shutdown on stacko ...

  10. unbuntu系统:python2.7安装pyspark

    以前在进行搜索引擎rank-svm排序模型训练时,直接使用python读取的HDFS日志文件.统计计算等预处理操作再进行svm模型,最终产生出训练模型.现在回想一下,数据预处理这一块完全可以使用spa ...