velocity模板路径


遇到的velocity加载模板时的路径问题。

于是查阅资料解决。最后综合velocity自己带的例子的example1和example2,改写了一个例子。怎样解决的在例子的注释中已经说的很明确。对于初学velocity的同志来说,这个例子可以是你参照学习的良好实例

Java代码   收藏代码
  1. /*  
  2.  * Licensed to the Apache Software Foundation (ASF) under one  
  3.  * or more contributor license agreements.  See the NOTICE file  
  4.  * distributed with this work for additional information  
  5.  * regarding copyright ownership.  The ASF licenses this file  
  6.  * to you under the Apache License, Version 2.0 (the  
  7.  * "License"); you may not use this file except in compliance  
  8.  * with the License.  You may obtain a copy of the License at  
  9.  *  
  10.  *   http://www.apache.org/licenses/LICENSE-2.0  
  11.  *  
  12.  * Unless required by applicable law or agreed to in writing,  
  13.  * software distributed under the License is distributed on an  
  14.  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY  
  15.  * KIND, either express or implied.  See the License for the  
  16.  * specific language governing permissions and limitations  
  17.  * under the License.      
  18.  */   
  19.   
  20. import  java.io.BufferedWriter;  
  21. import  java.io.OutputStreamWriter;  
  22. import  java.io.StringWriter;  
  23. import  java.util.ArrayList;  
  24. import  java.util.Properties;  
  25.   
  26. import  org.apache.velocity.Template;  
  27. import  org.apache.velocity.VelocityContext;  
  28. import  org.apache.velocity.app.Velocity;  
  29. import  org.apache.velocity.app.VelocityEngine;  
  30. import  org.apache.velocity.exception.MethodInvocationException;  
  31. import  org.apache.velocity.exception.ParseErrorException;  
  32.   
  33. /**  
  34.  * This class is a simple demonstration of how the Velocity Template Engine  
  35.  * can be used in a standalone application using the Velocity utility class.  
  36.  *  
  37.  * It demonstrates two of the 'helper' methods found in the org.apache.velocity.util.Velocity  
  38.  * class, mergeTemplate() and evaluate().  
  39.  *  
  40.  *  
  41.  * @author <a href="mailto:[email protected]">Geir Magnusson Jr.</a>  
  42.  * @version $Id: Example2.java 463298 2006-10-12 16:10:32Z henning $  
  43.  */   
  44.   
  45. public   class  Example2  
  46. {  
  47.       
  48.      public   static  ArrayList getNames()  
  49.         {  
  50.             ArrayList list = new  ArrayList();  
  51.   
  52.             list.add("ArrayList element 1" );  
  53.             list.add("ArrayList element 2" );  
  54.             list.add("ArrayList element 3" );  
  55.             list.add("ArrayList element 4" );  
  56.   
  57.             return  list;  
  58.         }  
  59.       
  60.     public   static   void  main( String args[] )  
  61.     {  
  62.         /* first, we init the runtime engine.  Defaults are fine. */   
  63.   
  64.         Properties p = new  Properties();  
  65.         //设置输入输出编码类型。和这次说的解决的问题无关   
  66.         p.setProperty(Velocity.INPUT_ENCODING, "UTF-8" );  
  67.         p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8" );  
  68.         //这里加载类路径里的模板而不是文件系统路径里的模板   
  69.         p.setProperty("file.resource.loader.class" "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader" );  
  70.         //也可以用下面方法指定一个绝对路径,不过这样要求你所有的模板都放在该路径下,是有局限的   
  71.         //p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, "模板路径");   
  72.         try   
  73.         {  
  74.             Velocity.init(p);  
  75.         }  
  76.         catch (Exception e)  
  77.         {  
  78.             System.out.println("Problem initializing Velocity : "  + e );  
  79.             return ;  
  80.         }  
  81.   
  82.         /* lets make a Context and put data into it */   
  83.   
  84.         VelocityContext context = new  VelocityContext();  
  85.   
  86.         context.put("name" "Velocity" );  
  87.         context.put("project" "阿帕奇" );  
  88.           
  89.         context.put("list" , getNames());  
  90.   
  91.         /* lets render a template */   
  92.   
  93.         StringWriter w = new  StringWriter();  
  94.   
  95.         try   
  96.         {  
  97.             Velocity.mergeTemplate("example2.vm" "UTF-8" , context, w );  
  98.         }  
  99.         catch  (Exception e )  
  100.         {  
  101.             System.out.println("Problem merging template : "  + e );  
  102.         }  
  103.   
  104.         System.out.println(" template : "  + w );  
  105.   
  106.         /*  
  107.          *  lets dynamically 'create' our template  
  108.          *  and use the evaluate() method to render it  
  109.          */   
  110.   
  111.         //这个例子也同时告诉我们可以先从文件系统读取一个文件到字符串,然后进行我们想要的操作   
  112.         String s = "We are using $project $name to render this." ;  
  113.         w = new  StringWriter();  
  114.   
  115.         try   
  116.         {  
  117.             Velocity.evaluate( context, w, "mystring" , s );  
  118.         }  
  119.         catch ( ParseErrorException pee )  
  120.         {  
  121.             /*  
  122.              * thrown if something is wrong with the  
  123.              * syntax of our template string  
  124.              */   
  125.             System.out.println("ParseErrorException : "  + pee );  
  126.         }  
  127.         catch ( MethodInvocationException mee )  
  128.         {  
  129.             /*  
  130.              *  thrown if a method of a reference  
  131.              *  called by the template  
  132.              *  throws an exception. That won't happen here  
  133.              *  as we aren't calling any methods in this  
  134.              *  example, but we have to catch them anyway  
  135.              */   
  136.             System.out.println("MethodInvocationException : "  + mee );  
  137.         }  
  138.         catch ( Exception e )  
  139.         {  
  140.             System.out.println("Exception : "  + e );  
  141.         }  
  142.   
  143.         System.out.println(" string : "  + w );  
  144.           
  145.         ///////////////////////////////////////////////////////   
  146.         //其他方法: 1分别指定路径,此方法可以设定不同的路径 (也可是相对的。在eclipse下是工程目录)   
  147.         try  {  
  148.             VelocityEngine velocityEngine = new  VelocityEngine();  
  149.             Properties properties = new  Properties();  
  150.             //也可以在这里指定绝对路径。当指定相对路径时, 在不同的环境下是有区别的。   
  151.             //比如把程序部署到tomcat以后,相对路径相对到哪里是个很恶心的事情。   
  152.             String basePath = "vm" ;  
  153.             //可设置绝对路径   
  154.             //String basePath = "F:/";   
  155.             properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, basePath);  
  156.             velocityEngine.init(properties);  
  157.             Template template = velocityEngine.getTemplate("example2.vm" );  
  158.             BufferedWriter writer = new  BufferedWriter(  
  159.                     new  OutputStreamWriter(System.out));  
  160.             template.merge(context, writer);  
  161.             writer.flush();  
  162.             writer.close();  
  163.         } catch  (Exception e) {  
  164.             e.printStackTrace();  
  165.         }  
  166.     }  
  167. }  
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.    
 */

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;

/**
 * This class is a simple demonstration of how the Velocity Template Engine
 * can be used in a standalone application using the Velocity utility class.
 *
 * It demonstrates two of the 'helper' methods found in the org.apache.velocity.util.Velocity
 * class, mergeTemplate() and evaluate().
 *
 *
 * @author <a href="mailto:[email protected]">Geir Magnusson Jr.</a>
 * @version $Id: Example2.java 463298 2006-10-12 16:10:32Z henning $
 */

public class Example2
{
	
	 public static ArrayList getNames()
	    {
	        ArrayList list = new ArrayList();

	        list.add("ArrayList element 1");
	        list.add("ArrayList element 2");
	        list.add("ArrayList element 3");
	        list.add("ArrayList element 4");

	        return list;
	    }
	
    public static void main( String args[] )
    {
        /* first, we init the runtime engine.  Defaults are fine. */

    	Properties p = new Properties();
    	//设置输入输出编码类型。和这次说的解决的问题无关
        p.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
        p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
        //这里加载类路径里的模板而不是文件系统路径里的模板
        p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        //也可以用下面方法指定一个绝对路径,不过这样要求你所有的模板都放在该路径下,是有局限的
        //p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, "模板路径");
        try
        {
            Velocity.init(p);
        }
        catch(Exception e)
        {
            System.out.println("Problem initializing Velocity : " + e );
            return;
        }

        /* lets make a Context and put data into it */

        VelocityContext context = new VelocityContext();

        context.put("name", "Velocity");
        context.put("project", "阿帕奇");
        
        context.put("list", getNames());

        /* lets render a template */

        StringWriter w = new StringWriter();

        try
        {
            Velocity.mergeTemplate("example2.vm", "UTF-8", context, w );
        }
        catch (Exception e )
        {
            System.out.println("Problem merging template : " + e );
        }

        System.out.println(" template : " + w );

        /*
         *  lets dynamically 'create' our template
         *  and use the evaluate() method to render it
         */

        //这个例子也同时告诉我们可以先从文件系统读取一个文件到字符串,然后进行我们想要的操作
        String s = "We are using $project $name to render this.";
        w = new StringWriter();

        try
        {
            Velocity.evaluate( context, w, "mystring", s );
        }
        catch( ParseErrorException pee )
        {
            /*
             * thrown if something is wrong with the
             * syntax of our template string
             */
            System.out.println("ParseErrorException : " + pee );
        }
        catch( MethodInvocationException mee )
        {
            /*
             *  thrown if a method of a reference
             *  called by the template
             *  throws an exception. That won't happen here
             *  as we aren't calling any methods in this
             *  example, but we have to catch them anyway
             */
            System.out.println("MethodInvocationException : " + mee );
        }
        catch( Exception e )
        {
            System.out.println("Exception : " + e );
        }

        System.out.println(" string : " + w );
        
        ///////////////////////////////////////////////////////
        //其他方法: 1分别指定路径,此方法可以设定不同的路径 (也可是相对的。在eclipse下是工程目录)
        try {
	        VelocityEngine velocityEngine = new VelocityEngine();
	        Properties properties = new Properties();
	        //也可以在这里指定绝对路径。当指定相对路径时, 在不同的环境下是有区别的。
	        //比如把程序部署到tomcat以后,相对路径相对到哪里是个很恶心的事情。
	        String basePath = "vm";
	        //可设置绝对路径
	        //String basePath = "F:/";
	        properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, basePath);
	        velocityEngine.init(properties);
	        Template template = velocityEngine.getTemplate("example2.vm");
	        BufferedWriter writer = new BufferedWriter(
	                new OutputStreamWriter(System.out));
	        template.merge(context, writer);
	        writer.flush();
            writer.close();
        } catch (Exception e) {
        	e.printStackTrace();
        }
    }
}

 

#         Properties p = new Properties(); 
#         //设置输入输出编码类型。和这次说的解决的问题无关 
#         p.setProperty(Velocity.INPUT_ENCODING, "UTF-8"); 
#         p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8"); 
#         //这里加载类路径里的模板而不是文件系统路径里的模板 
#         p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); 

就这几个参数,花了半个小时才把类路径连上.多谢楼主了.

你可能感兴趣的:(apache,eclipse,tomcat,.net,velocity)