freeMark页面静态化--简单实例

摘自:http://blog.csdn.net/oyzl68/article/details/6532117

一.在一个新建创建的web项目中添加freeMark的jar引用

  1.jar包下载地址http://freemarker.sourceforge.net/freemarkerdownload.html 

  2.maven地址,其中附带servletapi  

<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
  </dependency>
  <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker-gae</artifactId>
            <version>2.3.20</version>
</dependency>

二.在webroot下创建模板文件夹和模板文件,文件夹名称为templates,模板文件为hello.ftl,模板文件内容

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

三.创建响应模板servlet

public class Hello extends HttpServlet {
    private Configuration cfg;

    public void init() {
        // 初始化FreeMarker配置
        // 创建一个Configuration实例
        cfg = new Configuration();
        // 设置FreeMarker的模版文件位置
        cfg.setServletContextForTemplateLoading(getServletContext(),"templates");
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 建立数据模型
        Map root = new HashMap();
        // 放入对应数据key value
        root.put("user", "<h1>Test</h1>");
        // 取得模版文件
        Template t = cfg.getTemplate("hello.ftl");
        // 开始准备生成输出
        // 使用模版文件的charset作为本页面的charset
        // 使用text/html MIME-type
        response.setContentType("text/html; charset=" + t.getEncoding());
        PrintWriter out = response.getWriter();

        // 合并数据模型和模版,并将结果输出到out中
        try {
            t.process(root, out);// 用模板来开发servlet可以只在代码里面加入动态的数据
        } catch (TemplateException e) {
            throw new ServletException("处理Template模版中出现错误", e);
        }
    }
}

四.在修改web.xml,配置生成模板servlet mapping ,.do结尾

五.创建入口

<html>
<head>
<title>Hello FreeMarker Example</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
</head>
<body>
点击下面链接看看效果:
<hr>
<a href="hello.do">调用Hello模板</a> 
</body>
</html>

 

posted @ 2014-10-24 15:18  哎呦喂,我的小祖宗╰つ  阅读(215)  评论(0)    收藏  举报