Freemarker模板应用

来源:互联网 发布:cosplay软件下载 编辑:程序博客网 时间:2024/05/17 00:55

转载于:http://clq9761.iteye.com/blog/1341534

 

 FreeMarker是一个模板引擎,一个基于模板生成文本输出的通用工具,使用纯Java编写,
模板用servlet提供的数据动态地生成 HTML,模板语言是强大的直观的,编译器速度快,
输出接近静态HTML页面的速度。

 

一.Freemarker模板应用事例。
1.创建模板文件,在/resource/template目录下建立freemarkerLocal.ftl文件。

Java代码 复制代码 收藏代码
  1. ------------------普通变量获取-------------------   
  2. ${user}   
  3. ---------获取Map中属性--------------   
  4. ${latestProduct.url}   
  5. ${latestProduct.name}   
  6. -------自定义的indexOf方法变量-------   
  7. <#assign x = "something">   
  8. ${indexOf("met", x)}   
  9. ${indexOf("foo", x)}   
  10. ------自定义的转换器变量(转换小写为大写,以标签形式展现)----------------   
  11. blah1   
  12. <@upperCase>   
  13. blah2   
  14. blah3   
  15. </@upperCase>   
  16. blah4   
  17. ---------------共享变量的获取,在Configuration中设置---------------   
  18. <@to_upper>   
  19. ${company}   
  20. </@to_upper>  
[java] view plaincopy
  1. <span style="font-size:18px;">------------------普通变量获取-------------------  
  2. ${user}  
  3. ---------获取Map中属性--------------  
  4. ${latestProduct.url}  
  5. ${latestProduct.name}  
  6. -------自定义的indexOf方法变量-------  
  7. <#assign x = "something">  
  8. ${indexOf("met", x)}  
  9. ${indexOf("foo", x)}  
  10. ------自定义的转换器变量(转换小写为大写,以标签形式展现)----------------  
  11. blah1  
  12. <@upperCase>  
  13. blah2  
  14. blah3  
  15. </@upperCase>  
  16. blah4  
  17. ---------------共享变量的获取,在Configuration中设置---------------  
  18. <@to_upper>  
  19. ${company}  
  20. </@to_upper></span>  

 

2.代码解析模板文件输出。

Java代码 复制代码 收藏代码
  1. public class FreemarkerLocalTest {   
  2.        
  3.     public static void main(String[] args) throws Exception {   
  4.         /* 一般在应用的整个生命周期中你仅需要执行一下代码一次*/  
  5.         /* 创建一个合适的configuration */  
  6.         Configuration cfg = new Configuration();   
  7.            
  8.         // 设置模板加载的方式  
  9.         cfg.setDirectoryForTemplateLoading(   
  10.                 new File("D:/myspace/freemarker/resource/template"));   
  11.         // 方式二(从Web上下文获取)  
  12.         // void setServletContextForTemplateLoading(Object servletContext, String path);  
  13.            
  14.         // 设置模板共享变量,所有的模板都可以访问设置的共享变量  
  15.         cfg.setSharedVariable("to_upper"new UpperCaseTransform());   
  16.         cfg.setSharedVariable("company","FooInc.");   
  17.            
  18.         // 指定模板如何查看数据模型  
  19.         cfg.setObjectWrapper(new DefaultObjectWrapper());              
  20.            
  21.         // 如果从多个位置加载模板,可采用以下方式  
  22.         /**  
  23.         FileTemplateLoader ftl1 = new FileTemplateLoader(new File("/tmp/templates")); 
  24.         FileTemplateLoader ftl2 = new FileTemplateLoader(new File("/usr/data/templates")); 
  25.         ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(),""); 
  26.         TemplateLoader[] loaders = new TemplateLoader[] { ftl1, ftl2,ctl }; 
  27.         MultiTemplateLoader mtl = new MultiTemplateLoader(loaders); 
  28.         cfg.setTemplateLoader(mtl);**/  
  29.            
  30.         /* 而以下代码你通常会在一个应用生命周期中执行多次*/  
  31.         /*获取或创建一个模版*/  
  32.         Template temp = cfg.getTemplate("freemarkerLocal.ftl");   
  33.            
  34.         /*创建一个数据模型Create a data model */  
  35.         Map root = new HashMap();   
  36.         root.put("user""Big Joe");   
  37.         Map latest = new HashMap();   
  38.         root.put("latestProduct", latest);   
  39.         latest.put("url""products/greenmouse.html");   
  40.         latest.put("name""green mouse");   
  41.            
  42.         // 方法变量,indexOf为自己定义的方法变量  
  43.         root.put("indexOf"new IndexOfMethod());   
  44.            
  45.         // 转换器变量  
  46.         root.put("upperCase"new UpperCaseTransform());       
  47.            
  48.         /* 合并数据模型和模版*/  
  49.         Writer out = new OutputStreamWriter(System.out);   
  50.         temp.process(root, out);   
  51.         out.flush();   
  52.     }   
  53. }  
[java] view plaincopy
  1. <span style="font-size:18px;">public class FreemarkerLocalTest {  
  2.       
  3.     public static void main(String[] args) throws Exception {  
  4.         /* 一般在应用的整个生命周期中你仅需要执行一下代码一次*/  
  5.         /* 创建一个合适的configuration */  
  6.         Configuration cfg = new Configuration();  
  7.           
  8.         // 设置模板加载的方式  
  9.         cfg.setDirectoryForTemplateLoading(  
  10.                 new File("D:/myspace/freemarker/resource/template"));  
  11.         // 方式二(从Web上下文获取)  
  12.         // void setServletContextForTemplateLoading(Object servletContext, String path);  
  13.           
  14.         // 设置模板共享变量,所有的模板都可以访问设置的共享变量  
  15.         cfg.setSharedVariable("to_upper"new UpperCaseTransform());  
  16.         cfg.setSharedVariable("company","FooInc.");  
  17.           
  18.         // 指定模板如何查看数据模型  
  19.         cfg.setObjectWrapper(new DefaultObjectWrapper());             
  20.           
  21.         // 如果从多个位置加载模板,可采用以下方式  
  22.         /** 
  23.         FileTemplateLoader ftl1 = new FileTemplateLoader(new File("/tmp/templates")); 
  24.         FileTemplateLoader ftl2 = new FileTemplateLoader(new File("/usr/data/templates")); 
  25.         ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(),""); 
  26.         TemplateLoader[] loaders = new TemplateLoader[] { ftl1, ftl2,ctl }; 
  27.         MultiTemplateLoader mtl = new MultiTemplateLoader(loaders); 
  28.         cfg.setTemplateLoader(mtl);**/  
  29.           
  30.         /* 而以下代码你通常会在一个应用生命周期中执行多次*/  
  31.         /*获取或创建一个模版*/  
  32.         Template temp = cfg.getTemplate("freemarkerLocal.ftl");  
  33.           
  34.         /*创建一个数据模型Create a data model */  
  35.         Map root = new HashMap();  
  36.         root.put("user""Big Joe");  
  37.         Map latest = new HashMap();  
  38.         root.put("latestProduct", latest);  
  39.         latest.put("url""products/greenmouse.html");  
  40.         latest.put("name""green mouse");  
  41.           
  42.         // 方法变量,indexOf为自己定义的方法变量  
  43.         root.put("indexOf"new IndexOfMethod());  
  44.           
  45.         // 转换器变量  
  46.         root.put("upperCase"new UpperCaseTransform());      
  47.           
  48.         /* 合并数据模型和模版*/  
  49.         Writer out = new OutputStreamWriter(System.out);  
  50.         temp.process(root, out);  
  51.         out.flush();  
  52.     }  
  53. }  
  54. </span>  

 

3.自定义的方法变量类IndexOfMethod

Java代码 复制代码 收藏代码
  1. public class IndexOfMethod implements TemplateMethodModel {   
  2.        
  3.     public Object exec(List args) throws TemplateModelException {          
  4.         if (args.size() != 2) {   
  5.             throw new TemplateModelException("Wrong arguments");   
  6.         }   
  7.         // 返回第一个字符串首次出现在第二个字符串的位置  
  8.         return new SimpleNumber(((String) args.get(1))   
  9.                                 .indexOf((String) args.get(0)));   
  10.     }   
  11. }  
[java] view plaincopy
  1. <span style="font-size:18px;">public class IndexOfMethod implements TemplateMethodModel {  
  2.       
  3.     public Object exec(List args) throws TemplateModelException {         
  4.         if (args.size() != 2) {  
  5.             throw new TemplateModelException("Wrong arguments");  
  6.         }  
  7.         // 返回第一个字符串首次出现在第二个字符串的位置  
  8.         return new SimpleNumber(((String) args.get(1))  
  9.                                 .indexOf((String) args.get(0)));  
  10.     }  
  11. }</span>  

 

4.自定义的转换器变量类UpperCaseTransform

Java代码 复制代码 收藏代码
  1. /**  
  2.  * 转换器变量,自定义自己的转换器标签 
  3.  */  
  4. import freemarker.template.TemplateTransformModel;   
  5.   
  6. public class UpperCaseTransform implements TemplateTransformModel {   
  7.        
  8.     // 转换器接口方法,将会转换标签之间的内容,首先把标签之间的内容读取到Writer对象中,  
  9.     // 再由Writer对象对其中的内容施行转换处理,转换后的内容会再次存储到Writer 中  
  10.     public Writer getWriter(Writer out, Map args) {   
  11.         return new UpperCaseWriter(out);   
  12.     }   
  13.     private class UpperCaseWriter extends Writer {   
  14.         private Writer out;   
  15.   
  16.         UpperCaseWriter(Writer out) {   
  17.             this.out = out;   
  18.         }   
  19.         public void write(char[] cbuf, int off, int len) throws IOException {   
  20.             out.write(new String(cbuf, off, len).toUpperCase());   
  21.         }   
  22.   
  23.         public void flush() throws IOException {   
  24.             out.flush();   
  25.         }   
  26.         // 不用调用out.close,到达结束标签close会自动被调用  
  27.         public void close() {   
  28.                
  29.         }   
  30.     }   
  31. }  
[java] view plaincopy
  1. <span style="font-size:18px;">/** 
  2.  * 转换器变量,自定义自己的转换器标签 
  3.  */  
  4. import freemarker.template.TemplateTransformModel;  
  5.   
  6. public class UpperCaseTransform implements TemplateTransformModel {  
  7.       
  8.     // 转换器接口方法,将会转换标签之间的内容,首先把标签之间的内容读取到Writer对象中,  
  9.     // 再由Writer对象对其中的内容施行转换处理,转换后的内容会再次存储到Writer 中  
  10.     public Writer getWriter(Writer out, Map args) {  
  11.         return new UpperCaseWriter(out);  
  12.     }  
  13.     private class UpperCaseWriter extends Writer {  
  14.         private Writer out;  
  15.   
  16.         UpperCaseWriter(Writer out) {  
  17.             this.out = out;  
  18.         }  
  19.         public void write(char[] cbuf, int off, int len) throws IOException {  
  20.             out.write(new String(cbuf, off, len).toUpperCase());  
  21.         }  
  22.   
  23.         public void flush() throws IOException {  
  24.             out.flush();  
  25.         }  
  26.         // 不用调用out.close,到达结束标签close会自动被调用  
  27.         public void close() {  
  28.               
  29.         }  
  30.     }  
  31. }</span>  

 

二.自动生成代码应用


1.创建模板文件,在/resource/template目录下建立codeModel.ftl文件。

Java代码 复制代码 收藏代码
  1. package com.order.model;    
  2.   
  3. public class ${class} {    
  4.   
  5.   <#list properties as prop>   
  6.     private ${prop.type} ${prop.name};   
  7.   </#list>   
  8.   
  9.   <#list properties as prop>   
  10.     public ${prop.type} get${prop.name?cap_first}(){   
  11.       return ${prop.name};   
  12.     }   
  13.     public void set${prop.name?cap_first}(${prop.type} ${prop.name}){   
  14.       this.${prop.name} = ${prop.name};   
  15.     }   
  16.   </#list>   
  17.   
  18. }  
[java] view plaincopy
  1. <span style="font-size:18px;">package com.order.model;   
  2.   
  3. public class ${class} {   
  4.   
  5.   <#list properties as prop>  
  6.     private ${prop.type} ${prop.name};  
  7.   </#list>  
  8.   
  9.   <#list properties as prop>  
  10.     public ${prop.type} get${prop.name?cap_first}(){  
  11.       return ${prop.name};  
  12.     }  
  13.     public void set${prop.name?cap_first}(${prop.type} ${prop.name}){  
  14.       this.${prop.name} = ${prop.name};  
  15.     }  
  16.   </#list>  
  17.   
  18. }  
  19. </span>  

 

2.应用代码生成模板文件。

Java代码 复制代码 收藏代码
  1. public class GenerateCodeTest {   
  2.   
  3.     public static void main(String args[]) throws IOException,   
  4.                                                   TemplateException {   
  5.         Configuration cfg = new Configuration();   
  6.         cfg.setDirectoryForTemplateLoading(new File(   
  7.                 "D:/myspace/freemarker/resource/template/"));   
  8.         cfg.setObjectWrapper(new DefaultObjectWrapper());   
  9.   
  10.         /* 获取模板文件 */  
  11.         Template template = cfg.getTemplate("codeModel.ftl");   
  12.   
  13.         /* 模板数据 */  
  14.         Map<String, Object> root = new HashMap<String, Object>();   
  15.         root.put("class""Order");   
  16.         Collection<Map<String, String>> properties = new HashSet<Map<String, String>>();   
  17.         root.put("properties", properties);   
  18.   
  19.         /* 字段1 orderId */  
  20.         Map<String, String> orderId = new HashMap<String, String>();   
  21.         orderId.put("name""orderId");   
  22.         orderId.put("type""Long");   
  23.         properties.add(orderId);   
  24.   
  25.         /* 字段2 orderName */  
  26.         Map<String, String> orderName = new HashMap<String, String>();   
  27.         orderName.put("name""orderName");   
  28.         orderName.put("type""String");   
  29.         properties.add(orderName);   
  30.   
  31.         /* 字段3 money */  
  32.         Map<String, String> money = new HashMap<String, String>();   
  33.         money.put("name""money");   
  34.         money.put("type""Double");   
  35.         properties.add(money);   
  36.   
  37.         /* 生成输出到控制台 */  
  38.         Writer out = new OutputStreamWriter(System.out);   
  39.         template.process(root, out);   
  40.         out.flush();   
  41.   
  42.         /* 生成输出到文件 */  
  43.         File fileDir = new File("D:/generateCodeFile");   
  44.         // 创建文件夹,不存在则创建  
  45.         org.apache.commons.io.FileUtils.forceMkdir(fileDir);   
  46.         // 指定生成输出的文件  
  47.         File output = new File(fileDir + "/Order.java");   
  48.         Writer writer = new FileWriter(output);   
  49.         template.process(root, writer);   
  50.         writer.close();   
  51.     }   
  52. }  
[java] view plaincopy
  1. <span style="font-size:18px;">public class GenerateCodeTest {  
  2.   
  3.     public static void main(String args[]) throws IOException,  
  4.                                                   TemplateException {  
  5.         Configuration cfg = new Configuration();  
  6.         cfg.setDirectoryForTemplateLoading(new File(  
  7.                 "D:/myspace/freemarker/resource/template/"));  
  8.         cfg.setObjectWrapper(new DefaultObjectWrapper());  
  9.   
  10.         /* 获取模板文件 */  
  11.         Template template = cfg.getTemplate("codeModel.ftl");  
  12.   
  13.         /* 模板数据 */  
  14.         Map<String, Object> root = new HashMap<String, Object>();  
  15.         root.put("class""Order");  
  16.         Collection<Map<String, String>> properties = new HashSet<Map<String, String>>();  
  17.         root.put("properties", properties);  
  18.   
  19.         /* 字段1 orderId */  
  20.         Map<String, String> orderId = new HashMap<String, String>();  
  21.         orderId.put("name""orderId");  
  22.         orderId.put("type""Long");  
  23.         properties.add(orderId);  
  24.   
  25.         /* 字段2 orderName */  
  26.         Map<String, String> orderName = new HashMap<String, String>();  
  27.         orderName.put("name""orderName");  
  28.         orderName.put("type""String");  
  29.         properties.add(orderName);  
  30.   
  31.         /* 字段3 money */  
  32.         Map<String, String> money = new HashMap<String, String>();  
  33.         money.put("name""money");  
  34.         money.put("type""Double");  
  35.         properties.add(money);  
  36.   
  37.         /* 生成输出到控制台 */  
  38.         Writer out = new OutputStreamWriter(System.out);  
  39.         template.process(root, out);  
  40.         out.flush();  
  41.   
  42.         /* 生成输出到文件 */  
  43.         File fileDir = new File("D:/generateCodeFile");  
  44.         // 创建文件夹,不存在则创建  
  45.         org.apache.commons.io.FileUtils.forceMkdir(fileDir);  
  46.         // 指定生成输出的文件  
  47.         File output = new File(fileDir + "/Order.java");  
  48.         Writer writer = new FileWriter(output);  
  49.         template.process(root, writer);  
  50.         writer.close();  
  51.     }  
  52. }</span>  

 三.JSP调用模板文件输出。


1.首先创建模板文件,在WEB-INF/templates目录下建立test.ftl文件。

Java代码 复制代码 收藏代码
  1. Hello,${name}!  
[java] view plaincopy
  1. <span style="font-size:18px;">Hello,${name}!  
  2. </span>  

2.解析模板文件类,传入pageContext参数。

Java代码 复制代码 收藏代码
  1. public class FreemarkerTest {   
  2.        
  3.     public void execute(PageContext pageContext) throws Exception   
  4.     {           
  5.         Configuration cfg = new Configuration();           
  6.         // 设置模板的路径  
  7.         cfg.setServletContextForTemplateLoading(pageContext.getServletContext(),    
  8.                                                 "WEB-INF/templates");           
  9.         Map root = new HashMap();   
  10.         root.put("name""Tom");           
  11.         // 获取模板文件  
  12.         Template t = cfg.getTemplate("test.ftl");           
  13.         Writer out = pageContext.getResponse().getWriter();           
  14.         t.process(root, out);   
  15.     }   
  16. }  
[java] view plaincopy
  1. <span style="font-size:18px;">public class FreemarkerTest {  
  2.       
  3.     public void execute(PageContext pageContext) throws Exception  
  4.     {          
  5.         Configuration cfg = new Configuration();          
  6.         // 设置模板的路径  
  7.         cfg.setServletContextForTemplateLoading(pageContext.getServletContext(),   
  8.                                                 "WEB-INF/templates");          
  9.         Map root = new HashMap();  
  10.         root.put("name""Tom");          
  11.         // 获取模板文件  
  12.         Template t = cfg.getTemplate("test.ftl");          
  13.         Writer out = pageContext.getResponse().getWriter();          
  14.         t.process(root, out);  
  15.     }  
  16. }  
  17. </span>  

 3.创建JSP文件调用输出。

Html代码 复制代码 收藏代码
  1. <%@ page language="java" contentType="text/html; charset=GB2312"  
  2.     pageEncoding="GB2312"%>  
  3. <%@page import="com.freemarker.test.FreemarkerTest;"%>  
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"    
  5.     "http://www.w3.org/TR/html4/loose.dtd">  
  6. <html>  
  7.     <head>  
  8.         <meta http-equiv="Content-Type" content="text/html; charset=GB2312">  
  9.         <title>HelloWorld</title>  
  10.     </head>  
  11.     <body>  
  12.         <%   
  13.             FreemarkerTest c1 = new FreemarkerTest();   
  14.             c1.execute(pageContext);   
  15.         %>  
  16.     </body>  
  17. </html>  
[html] view plaincopy
  1. <span style="font-size:18px;"><%@ page language="java" contentType="text/html; charset=GB2312"  
  2.     pageEncoding="GB2312"%>  
  3. <%@page import="com.freemarker.test.FreemarkerTest;"%>  
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"   
  5.     "http://www.w3.org/TR/html4/loose.dtd">  
  6. <html>  
  7.     <head>  
  8.         <meta http-equiv="Content-Type" content="text/html; charset=GB2312">  
  9.         <title>HelloWorld</title>  
  10.     </head>  
  11.     <body>  
  12.         <%  
  13.             FreemarkerTest c1 = new FreemarkerTest();  
  14.             c1.execute(pageContext);  
  15.         %>  
  16.     </body>  
  17. </html></span>  

 四.Servlet调用模板文件生成html文件进行页面展示。


1.创建模板文件,在WebRoot/index目录下建立test.ftl文件。 

Java代码 复制代码 收藏代码
  1. <html>   
  2. <body>   
  3.    用户名:${userName}<br>   
  4.    邮&nbsp;&nbsp;箱:${email}   
  5. </body>   
  6. </html>  
[java] view plaincopy
  1. <span style="font-size:18px;"><html>  
  2. <body>  
  3.    用户名:${userName}<br>  
  4.    邮&nbsp;&nbsp;箱:${email}  
  5. </body>  
  6. </html></span>  

 

2.创建Servlet文件解析模板文件并生成html文件进行页面输出。

Java代码 复制代码 收藏代码
  1. public class FreemarkerServletTest extends HttpServlet {   
  2.   
  3.     public FreemarkerServletTest() {   
  4.            super();   
  5.     }   
  6.     public void destroy() {   
  7.        super.destroy();    
  8.     }   
  9.     public void doGet(HttpServletRequest request, HttpServletResponse response)   
  10.         throws ServletException, IOException {   
  11.         doPost(request, response);   
  12.     }   
  13.     public void doPost(HttpServletRequest request, HttpServletResponse response)   
  14.         throws ServletException, IOException {   
  15.        //生成html后的文件  
  16.        String path = getServletContext().getRealPath("/") + "index.htm";   
  17.        System.out.println(path);   
  18.        try {   
  19.         freemarker(request, "test.ftl", path, "index");   
  20.        } catch (Exception e) {   
  21.         e.printStackTrace();   
  22.        }   
  23.        //跳转到刚生成的html文件中  
  24.        request.getRequestDispatcher("/index.htm").forward(request, response);   
  25.     }   
  26.   
  27.     /**  
  28.     * 生成静态文件  
  29.     * @param request 
  30.     * @param ftl ftl文件 
  31.     * @param html 生成html后的文件 
  32.     * @param file 存放ftl文件的路径 
  33.     * @throws Exception 
  34.     */  
  35.     public void freemarker(HttpServletRequest request,String ftl,   
  36.                         String html,String file) throws Exception {   
  37.        Configuration cfg = new Configuration();       
  38.        // 设置加载模板的路径  
  39.        cfg.setServletContextForTemplateLoading(getServletContext(),"/" + file);   
  40.        cfg.setEncoding(Locale.getDefault(), "GB18030");   
  41.          
  42.        //获得模板并设置编码  
  43.        Template tep = cfg.getTemplate(ftl);   
  44.        tep.setEncoding("GB18303");   
  45.           
  46.        //新建输出,生成html文件  
  47.        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(html),"GB18030"));   
  48.        //设置值   
  49.        Map map = new HashMap();   
  50.        map.put("userName""wxj");   
  51.        map.put("email""jxauwxj@126.com");   
  52.        // 解析并输出  
  53.        tep.process(map, out);   
  54.     }   
  55.   
  56.     public void init() throws ServletException {           
  57.     }   
  58. }  
[java] view plaincopy
  1. <span style="font-size:18px;">public class FreemarkerServletTest extends HttpServlet {  
  2.   
  3.     public FreemarkerServletTest() {  
  4.            super();  
  5.     }  
  6.     public void destroy() {  
  7.        super.destroy();   
  8.     }  
  9.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  10.         throws ServletException, IOException {  
  11.         doPost(request, response);  
  12.     }  
  13.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  14.         throws ServletException, IOException {  
  15.        //生成html后的文件  
  16.        String path = getServletContext().getRealPath("/") + "index.htm";  
  17.        System.out.println(path);  
  18.        try {  
  19.         freemarker(request, "test.ftl", path, "index");  
  20.        } catch (Exception e) {  
  21.         e.printStackTrace();  
  22.        }  
  23.        //跳转到刚生成的html文件中  
  24.        request.getRequestDispatcher("/index.htm").forward(request, response);  
  25.     }  
  26.   
  27.     /** 
  28.     * 生成静态文件 
  29.     * @param request 
  30.     * @param ftl ftl文件 
  31.     * @param html 生成html后的文件 
  32.     * @param file 存放ftl文件的路径 
  33.     * @throws Exception 
  34.     */  
  35.     public void freemarker(HttpServletRequest request,String ftl,  
  36.                         String html,String file) throws Exception {  
  37.        Configuration cfg = new Configuration();      
  38.        // 设置加载模板的路径  
  39.        cfg.setServletContextForTemplateLoading(getServletContext(),"/" + file);  
  40.        cfg.setEncoding(Locale.getDefault(), "GB18030");  
  41.         
  42.        //获得模板并设置编码  
  43.        Template tep = cfg.getTemplate(ftl);  
  44.        tep.setEncoding("GB18303");  
  45.          
  46.        //新建输出,生成html文件  
  47.        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(html),"GB18030"));  
  48.        //设置值  
  49.        Map map = new HashMap();  
  50.        map.put("userName""wxj");  
  51.        map.put("email""jxauwxj@126.com");  
  52.        // 解析并输出  
  53.        tep.process(map, out);  
  54.     }  
  55.   
  56.     public void init() throws ServletException {          
  57.     }  
  58. }</span>  

 

3.web.xml文件进行servlet配置。

Xml代码 复制代码 收藏代码
  1. <servlet>      
  2.     <servlet-name>FreemarkerServletTest</servlet-name>  
  3.     <servlet-class>com.servlet.FreemarkerServletTest</servlet-class>  
  4. </servlet>  
  5.   
  6. <servlet-mapping>  
  7.     <servlet-name>FreemarkerServletTest</servlet-name>  
  8.     <url-pattern>/servlet/FreemarkerServletTest</url-pattern>  
  9. </servlet-mapping>  
[xml] view plaincopy
  1. <span style="font-size:18px;"><servlet>     
  2.     <servlet-name>FreemarkerServletTest</servlet-name>  
  3.     <servlet-class>com.servlet.FreemarkerServletTest</servlet-class>  
  4. </servlet>  
  5.   
  6. <servlet-mapping>  
  7.     <servlet-name>FreemarkerServletTest</servlet-name>  
  8.     <url-pattern>/servlet/FreemarkerServletTest</url-pattern>  
  9. </servlet-mapping></span>  

 

4.页面访问如下Url:
 
http://localhost:8080/freemarkerWeb/servlet/FreemarkerServletTest  
输出结果如下:

Java代码 复制代码 收藏代码
  1. 用户名:wxj   
  2. 邮  箱:jxauwxj@126.com  
[java] view plaincopy
  1. <span style="font-size:18px;">用户名:wxj  
  2. 邮  箱:jxauwxj@126.com</span>  

 

同时会在部署环境的目录下生成index.htm文件。

0 0
原创粉丝点击