package com.freemarker.servlet;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class HelloServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private Configuration cfg;
public void init(){
//初始化FreeMarker配置
//创建一个Configuration实例
cfg = new Configuration();
//设置FreeMarker的模板文件位置
cfg.setServletContextForTemplateLoading(getServletContext(), "WEB-INF/templates");
}
public void service (HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException{
//建立数据模型
Map root = new HashMap();
//测试${}
root.put("name", "中国");
root.put("msg", "web的第一个FreeMarker实例");
//测试<#if></#if>
root.put("a", new Integer(1));
root.put("b", "1");
boolean flag = true;
root.put("flag", flag);
//测试<#list>
List numbers = new ArrayList();
numbers.add(1);
numbers.add(2);
numbers.add(3);
root.put("numbers", numbers);
//测试
root.put("userName", new String());
String[] seq = {"a","b","c","d","e"};
root.put("seq", seq);
//内建函数
root.put("大于小于", "<>");
//测试date
Date date = new Date();
root.put("date", date);
//取得模型文件
Template t = cfg.getTemplate("templates.ftl");
//开始准备生成输出
//使用模板文件的charset作为本页面的charset
//使用text/html MIME-type
response.setContentType("text/html;charset=" + t.getEncoding());
Writer out = response.getWriter();
//合并数据模型和模板,并将结果输出到out中
try {
t.process(root, out);
} catch (Exception e) {
throw new ServletException("处理Template模板中出项错误" , e);
}
}
}
评论7
最新资源