ITeye博客

FreeMarker简单应用

grey2 · 2010-08-30 22:07 · View模板 · Web前端 · Markdown

第一章 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

二、实例应用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; //取得类名        	
    	action2 = str; //取得方法名
    }

    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的格式。如下 跳转到模板 6、模板页面的存放位置必须page.setTemplate("WEB-INF/free.html")相一致

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。