`
lxy2330
  • 浏览: 465723 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

velocity模板路径

    博客分类:
  • java
阅读更多


遇到的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:geirm@optonline.net">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:geirm@optonline.net">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"); 

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

分享到:
评论

相关推荐

    Velocity模板使用指南中文版

    - **初始化**: Velocity 引擎加载配置,如模板路径、缓存策略等。 - **创建上下文**: 填充需要在模板中使用的数据。 - **合并模板**: 将上下文中的数据与模板结合,生成最终的 HTML 或其他格式的输出。 - **输出**: ...

    Velocity模板解析

    Velocity模板的主要目标是将业务逻辑与显示逻辑分离,让开发者专注于内容的展示,而不用关心页面布局和设计。 Velocity的工作原理基于模板语言和Java对象的结合。在模板中,开发者可以使用特定的指令(如#set、#if...

    SpringBoot Velocity 代码生成模板

    在Spring Boot项目中,使用Velocity模板引擎可以自定义生成代码,如Mapper、Mapper.xml、Service、Controller等。Mapper是数据库操作层,通常配合MyBatis框架使用;Mapper.xml包含SQL语句;Service是业务逻辑层,...

    SpringBoot集成Mybatis,velocity模板展示数据

    本项目主要探讨的是如何将SpringBoot与Mybatis、Velocity模板引擎进行整合,以便更高效地展示和处理数据。 首先,让我们深入了解SpringBoot的核心特性。SpringBoot的设计理念是“约定优于配置”,它内置了Tomcat...

    SpringBoot集成Mybatis,velocity模板

    5. **使用Velocity模板**:创建Velocity模板文件(如`templates/email.vm`),然后在服务类中使用VelocityContext填充数据,并通过VelocityEngine渲染模板。 ```java // EmailService.java public void sendEmail...

    velocity实现邮件模板定制

    5. **合并模板与数据**:使用`Velocity.mergeTemplate()`方法,传入模板文件路径和上下文,生成最终的邮件内容字符串。 6. **发送邮件**:将生成的邮件内容传递给邮件服务API,完成发送。 关于源码,Velocity的...

    Velocity模板邮件发送例子(Spring框架)(可通用,支持多扩展)

    这包括设置模板路径、编码、资源加载器等配置项,确保Spring能够正确地找到和处理Velocity模板。 ```xml &lt;bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"&gt; ...

    velocity入门使用教程

    Velocity模板语言(Velocity Template Language,简称VTL)是Velocity的核心,它提供了一种简单但功能强大的模板语言,允许用户通过模板文件引用Java对象属性,结合数据模型动态生成内容。 在本教程中,我们将介绍...

    Velocity模板引擎 v2.2.0.zip

    在Velocity模板中,开发者可以使用特定的指令(如#$或##)来插入Java代码片段,这些代码会被引擎解析并执行,然后将结果插入到模板的相应位置。这样,模板设计者可以专注于页面布局,而程序员则关注业务逻辑。 ...

    velocity文档(Velocity1.4java开发指南中文版,Velocity1.4模板使用指南中文版中文版)

    Velocity 是一个开源的 Java 模板引擎,它允许开发者将静态页面内容与动态数据分离,使得开发者可以专注于业务逻辑,而设计师则可以专心于页面设计。Velocity1.4 是该引擎的一个版本,发布于较早时期,但其基本原理...

    Freemarker和Velocity的eclipse插件

    `VelocityWebEdit-1.0.8.zip`这个插件是针对Velocity模板的Eclipse扩展,它可以提供 Velocity模板的语法高亮、代码提示、代码格式化等功能,帮助开发者更好地管理和调试Velocity模板文件(`.vm`)。 Eclipse插件的...

    velocity(eclipse插件)

    这个插件提供了对Velocity模板语言(VTL)的语法高亮、代码提示、错误检查等功能,极大地提升了开发效率。 **一、安装与配置** 1. **下载与安装**: 可以从Eclipse Marketplace或官方站点下载Velocity插件。在...

    Velocity用户手册 中文版

    ** Velocity 模板引擎概述 ** Velocity 是一个开源的Java模板引擎,它允许开发者将HTML、XML或者其他格式的文档与应用程序逻辑分离。Velocity 提供了一种简单但强大的模板语言,使得开发者可以专注于页面布局和设计...

    Velocity学习Web项目

    在Struts 1.x版本中,视图通常由JSP页面来实现,但也可以使用Velocity模板来替代,因为Velocity提供了更简洁的语法和更好的性能。 在集成Velocity之前,我们需要确保我们的环境已经配置了Struts 1.x和Velocity。这...

    velocity-1.5.jar,velocity-1.6.2-dep.jar,velocity-tools-1.3.jar

    在实际使用中,开发者需要将这些JAR文件添加到项目的类路径中,然后可以通过创建VelocityContext对象,填充数据,最后使用Velocity Engine渲染模板。这整个过程是完全独立于具体的服务器环境的,使得Velocity成为一...

    Velocity模板技术

    标题:Velocity模板技术 描述与知识点: Velocity模板技术是一种用于分离HTML、XML、PDF等文档的格式和数据的模板引擎。它广泛应用于Java Web开发中,尤其在MVC架构下,用于视图层的渲染。Velocity的核心优势在于...

    velocity所需的jar包

    这个文件提供了对Velocity模板语言(VTL)的支持,使得开发者能够用简单的文本格式定义动态内容,并在运行时用Java对象的数据填充这些模板。 其次,`velocity-tools.jar`是Velocity Tools项目的一部分,它提供了...

    velocity中文

    Velocity模板语言是一种标记语言,用于描述如何在模板中插入动态内容。VTL的语法简洁,主要包括以下几个关键概念: - `${}`:这是Velocity中的变量引用符号,用于插入Java对象的属性值。 - `#set()`:用于设置变量...

Global site tag (gtag.js) - Google Analytics