简体   繁体   中英

How to use Velocity template inside java class

I am trying to use a velocity template inside java class below is my code

 VelocityEngine ve = new VelocityEngine();
 ve.init();
 VelocityContext context = new VelocityContext();       
 context.put("object", someobject);
 Template t = ve.getTemplate("template.vm");
 StringWriter writer = new StringWriter();
 t.merge(context, writer);

The code throws resource not found at the line

ve.getTemplate("template.vm")

regardless of how i give the path it is not taking.

what should be my path for that template.vm

it is not inside the web-inf folder but inside the web directory.

I found the problem to be the properties not being set properly

Properties velocityProperties = new Properties();
velocityProperties.put("resource.loader", "class");
velocityProperties.put("class.resource.loader.description", "Velocity Classpath Resource Loader");
velocityProperties.put("class.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            velocityProperties.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.FileResourceLoader");
velocityProperties.put("file.resource.loader.path","/");
velocityProperties.put("file.resource.loader.cache","false");

ve.init(velocityProperties

once i put this it is picking up my template.

);

In your app conf xml you must specify the bean and where template are located, also the extension of templates. In my case:

<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
    <property name="resourceLoaderPath" value="/WEB-INF/views/" />
</bean>

<!-- View resolvers can also be configured with ResourceBundles or XML files.
    If you need different view resolving based on Locale, you have to use the
    resource bundle resolver. -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
    <property name="cache" value="true" />
    <property name="prefix" value="" />
    <property name="suffix" value=".vm" />
    <property name="toolboxConfigLocation" value="/WEB-INF/velocity-toolbox.xml" />
</bean>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM