当前位置: 代码迷 >> Web前端 >> FreeMarker简略应用
  详细解决方案

FreeMarker简略应用

热度:250   发布时间:2012-11-04 10:42:41.0
FreeMarker简单应用
第一章 FreeMarker简单应用
一、简单实例
1、创建Web application:freeMarker,导入reemarker-2.3.16\lib\freemarker.jar
2、创建Servlet:ActionServlet.java
package com.zh.servlet;

import …………;

public class ActionServlet extends HttpServlet {
    //声明Configuration对象
private Configuration cfg;
       //在实例化Servlet时初始化Configuration
public void init() throws ServletException {
// Initialize the FreeMarker configuration;
         // 初始化FreeMarker的Configuration
        // - 创建Configuration实例
cfg = new Configuration();
// - 设置模板文件的目录路径
cfg.setServletContextForTemplateLoading
                                        (getServletContext(), null); }

protected void doPost(HttpServletRequest request,
                       HttpServletResponse response)
                       throws ServletException, IOException {
//Build a data-model:创建数据模型
Map root = new HashMap();
root.put("message", "hello world!");

//Get the templat object:取得一个模板
Template t = cfg.getTemplate("free.html");

//Get a out flow:取得输出流
Writer out = response.getWriter();

//Merge the data-model and Template
                  //:合并:数据模型+模板=输出
try {
t.process(root, out);
                           //t为模板,加入数据模型root
} catch (TemplateException e) {
    throw new ServletException(
                         "Error while processing template", e);
}
}

protected void doGet(HttpServletRequest request,
                              HttpServletResponse response)
                             throws ServletException, IOException {
this.doPost(request, response);
}
}
3、创建模板:free.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
${message}
</body>
</html>
这样就正确的跳转到free.html页面并输出了:hello world!
简单总结:
1 初始化Configuration:Configuration cfg = new Configuration();
2 设置模板路径:此种方式是设置为应用程序根目录下:
cfg.setServletContextForTemplateLoading(getServletContext(), null);
可更改null为“xxDirectory/xxDirectory”某个目录下。
3 创建数据模型:Map root = new HashMap();
   添加数据:root.put("message", "hello world!");
4 取得模板:Template t = cfg.getTemplate("free.html");
直接从cfg.set……设置的目录查找此“模板”,如果参数2为null,直接从根目录下查找,当然模板也可以写为:Template t = cfg.getTemplate("xxDirectory/free.html")
5 取得输出流:Write out = response.getWrite();
6 合并数据模型+模板:t.process(root, out);
此方法直接会使浏览器跳转到指定“模板”页面,而不是forward/sendRedirect等方式。

二、实例应用2
在前面实例了的基础上,进一步的操作。
1、创建Page.java,它对Template、Map进一步封装
package com.zh.servlet;
import java.util.HashMap;
import java.util.Map;

public class Page {
private String template; //模板路径及文件
private String forward;  //跳转页面
private Map root = new HashMap(); //数据模型

//取得模板
public String getTemplate() {
return template;
}
public void setTemplate(String template) {
            //设置模板,跳转页面为空
forward = null;
this.template = template;
}
//向数据模型添加数据
public void put(String name, Object value) {
root.put(name, value);
}

public void put(String name, int value) {
        root.put(name, new Integer(value));
    }
   
    public void put(String name, double value) {
        root.put(name, new Double(value));
    }

    public void put(String name, boolean value) {
        root.put(name, new Boolean(value));
    }
    //取得跳转页面
public String getForward() {
return forward;
}
public void setForward(String forward) {//设置跳转页面
this.template = null;
this.forward = forward;
}
public Map getRoot() {//取得模型
return root;
}
public void setRoot(Map root) {
this.root = root;
}

}

2、创建src/com/zh/config/action.properties
#class name + method name
#请求路径/类名/方法名.page
#Test
test.driver = com.zh.action.Test
test.mm = mm
3、修改ActionServlet.java的doGet()方法
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

String action = request.getServletPath();//取得请求路径
String action1 = null; //类名
String action2 = null; //方法名
//从请求路径路径中取出类名
if (action == null) action = "index";
        if (action.startsWith("/")) action = action.substring(1);
        if (action.lastIndexOf(".") != -1) {
            action = action.substring(0, action.lastIndexOf("."));
        }
        if (action.indexOf("/") != -1) {
        String[] str = action.split("/");
        action1 = str[0]; //取得类名       
        action2 = str[1]; //取得方法名
        }

        Properties pro = new Properties();
        pro.load(Thread.currentThread().getContextClassLoader()
             .getResourceAsStream("com/zh/config/action.properties"));
        String driver = pro.getProperty(action1 + ".driver");
        String me = pro.getProperty(action1 + "." + action2);
       
        //通过反射调用方法,传递参数request/page
        Page page = new Page();
        if(!(driver == null && me == null)) {
        try {
   Class<?> c = Class.forName(driver);
   Method mehtod = c.getMethod(me,
                 new Class[]{HttpServletRequest.class, Page.class});
   mehtod.invoke(c.newInstance(),
                       new Object[] {request, page});
} catch (Exception e) {
e.printStackTrace();
}
       
        }
               
        if(page != null && page.getTemplate() != null) {
        Template t = cfg.getTemplate(page.getTemplate());
       
// //Get a out flow
        Writer out = response.getWriter();

        //Merge the data-model and Template

try {
t.process(page.getRoot(), out); } catch (TemplateException e) {
    throw new ServletException("Error while processing ", e);
}

        } else {
        request.getRequestDispatcher(page.getForward())
                                     .forward(request, response);
        }
}
4、编写action,方法的声明必须固定:例:com/zh/action/Test.java
public class Test {
public void mm(HttpServletRequest request, Page page) {
page.put("message", "hello world!");
List list = new ArrayList();
list.add("01aaaaa");
list.add("02aaaaa");
list.add("03aaaaa");    //添加
page.put("alist", list);  //添加List
page.setTemplate("WEB-INF/free.html");//设置模板
}
}
自定义的类与方法必须在action.properties中配置,同上。
5、在请求地址中必须写成:类名/方法名.page的格式。如下
<a href="test\mm.page">跳转到模板</a>
6、模板页面的存放位置必须page.setTemplate("WEB-INF/free.html")相一致
<body>
${message}<br>
<#list alist as a>
${a}<br>
</#list>
</body>
输出结果:
hello world!
01aaaaa
02aaaaa
03aaaaa