去看
org.apache.velocity.runtime.resource.loader.DataSourceResourceLoader
的API文档。

解决方案 »

  1.   

    晕死了,APi文档里有DataSourceResourceLoader的详细介绍,居然jar包里没有....给个简单实现罢:package com.saro.custom.velocity;import org.apache.velocity.runtime.resource.loader.ResourceLoader;
    import org.apache.velocity.runtime.resource.Resource;
    import org.apache.velocity.exception.ResourceNotFoundException;
    import org.apache.commons.collections.ExtendedProperties;import java.io.InputStream;
    import java.io.ByteArrayInputStream;/**
     * User: Saro
     * Date: 2006-3-17
     * Time: 19:02:29
     */
    public class StringResourceLoader extends ResourceLoader {    public void init( ExtendedProperties configuration){
        }    public synchronized InputStream getResourceStream( String templateString )
                throws ResourceNotFoundException{
            InputStream result = null;        if (templateString == null || templateString.length() == 0) {
                throw new ResourceNotFoundException ("No template string provided");
            }
            result=new ByteArrayInputStream(templateString.getBytes());
            return result;
        }    public boolean isSourceModified(Resource resource) {
            return false;
        }    public long getLastModified(Resource resource) {
            return 0;
        }
    }然后,测试代码:
        public static void testVelocity() {
            try {
                //Velocity.init("WEB-INF/velocity.properties");
                Properties p=new Properties();
                p.put("input.encoding","UTF-8");
                p.put("output.encoding","UTF-8");
                p.put("resource.loader","srl");
                p.put("srl.resource.loader.class","com.saro.custom.velocity.StringResourceLoader");
                Velocity.init(p);
                VelocityContext context = new VelocityContext();            context.put("coolman", "Rodjohnson");
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("r.txt"),"UTF-8"));
                Template tt=Velocity.getTemplate("coolman is ${coolman}","UTF-8");
                tt.merge(context,writer);
                writer.flush();
                writer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }    }