`
littie1987
  • 浏览: 130774 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论

Velocity加载classpath下模板

    博客分类:
  • Java
 
阅读更多

Velocity默认是加载文件系统中的模板,如果希望加载classpath下的模板的话,需要更换他的加载器

 Properties properties=new Properties();
	        //设置velocity资源加载方式为class
 properties.setProperty("resource.loader", "class");
	        //设置velocity资源加载方式为file时的处理类
 properties.setProperty("class.resource.loader.class", 
                        "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
VelocityEngine ve = new VelocityEngine(properties);   

 

 

默认情况是加载文件系统

        VelocityEngine ve = new VelocityEngine();  
        //设置参数
        ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, templatepath);//加载文件系统

 

另附完整代码

 Properties properties=new Properties();
	        //设置velocity资源加载方式为class
	     properties.setProperty("resource.loader", "class");
	        //设置velocity资源加载方式为file时的处理类
	     properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
	        
        VelocityEngine ve = new VelocityEngine(properties);   
        //设置参数
      //  ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, templatepath);
        //处理中文问题
        ve.setProperty(Velocity.INPUT_ENCODING,"utf-8");
        ve.setProperty(Velocity.OUTPUT_ENCODING,"utf-8");
        try  {
            //初始化模板
            ve.init();
            //Velocity模板的名称 
            Template template = ve.getTemplate(templatename,"utf-8"); 
            Writer mywriter = new PrintWriter(outfile,"utf-8");
            template.merge(vc, mywriter);
            mywriter.flush();           
            mywriter.close();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("写模板文件"+templatename+"失败", e);
            throw e;
        }

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics