Nur eine einfache, eigenständige Geschwindigkeits-App, die auf der Maven-Struktur basiert. Hier ist der Code-Ausschnitt, der in Scala geschrieben wurde, um die Vorlage helloworld.vm
im Ordner ${basedir}/src/main/resources
zu rendern:
com.ggd543.velocitydemo
import org.Apache.velocity.app.VelocityEngine
import org.Apache.velocity.VelocityContext
import Java.io.StringWriter
/**
* @author ${user.name}
*/
object App {
def main(args: Array[String]) {
//First , get and initialize an engine
val ve = new VelocityEngine();
ve.init();
//Second, get the template
val resUrl = getClass.getResource("/helloworld.vm")
val t = ve.getTemplate("helloworld.vm"); // not work
// val t = ve.getTemplate("/helloworld.vm"); // not work
// val t = ve.getTemplate(resUrl.toString); // not work yet
//Third, create a context and add data
val context = new VelocityContext();
context.put("name", "Archer")
context.put("site", "http://www.baidu.com")
//Finally , render the template into a StringWriter
val sw = new StringWriter
t.merge(context, sw)
println(sw.toString);
}
}
beim Kompilieren und Ausführen des Programms wurde folgende Fehlermeldung angezeigt:
2012-1-29 14:03:59 org.Apache.velocity.runtime.log.JdkLogChute log
严重: ResourceManager : unable to find resource '/helloworld.vm' in any resource loader.
Exception in thread "main" org.Apache.velocity.exception.ResourceNotFoundException: Unable to find resource '/helloworld.vm'
at org.Apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.Java:474)
at org.Apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.Java:352)
at org.Apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.Java:1533)
at org.Apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.Java:1514)
at org.Apache.velocity.app.VelocityEngine.getTemplate(VelocityEngine.Java:373)
at com.ggd543.velocitydemo.App$.main(App.scala:20)
at com.ggd543.velocitydemo.App.main(App.scala)
at Sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at Sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.Java:39)
at Sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.Java:25)
at Java.lang.reflect.Method.invoke(Method.Java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.Java:120)
Process finished with exit code 1
Große Frage - Ich habe mein Problem heute mit Ecilpse wie folgt gelöst:
Fügen Sie Ihre Vorlage in derselben Ordnerhierarchie wie Ihr Quellcode ein (nicht in einer separaten Ordnerhierarchie, auch wenn Sie sie in den Erstellungspfad aufnehmen).
Verwenden Sie in Ihrem Code einfach die folgenden Codezeilen (vorausgesetzt, Sie möchten nur, dass das Datum als Daten übergeben wird):
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
VelocityContext context = new VelocityContext();
context.put("date", getMyTimestampFunction());
Template t = ve.getTemplate( "templates/email_html_new.vm" );
StringWriter writer = new StringWriter();
t.merge( context, writer );
Sehen Sie, wie wir VelocityEngine zuerst sagen, dass sie im Klassenpfad aussehen soll. Ohne das wüsste es nicht wo ich suchen muss.
Ich lege meine .vm unter den src/main/resources/templates
, dann lautet der Code:
Properties p = new Properties();
p.setProperty("resource.loader", "class");
p.setProperty("class.resource.loader.class", "org.Apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init( p );
VelocityContext context = new VelocityContext();
Template template = Velocity.getTemplate("templates/my.vm");
das funktioniert im Webprojekt.
In Eclipse funktioniert Velocity.getTemplate ("my.vm"), da Velocity nach der .vm-Datei in src/main/resources/oder src/main/resources/templates sucht. In Webprojekt müssen wir jedoch Velocity.getTemplate verwenden ("templates/my.vm");
Sie können es einfach so verwenden:
Template t = ve.getTemplate("./src/main/resources/templates/email_html_new.vm");
Es klappt.
Stellen Sie sicher, dass Sie einen ordnungsgemäß konfigurierten Ressourcenlader haben. Informationen zur Auswahl und Konfiguration eines Ressourcenladers finden Sie in der Velocity-Dokumentation: http://velocity.Apache.org/engine/releases/velocity-1.7/developer-guide.html#resourceloaders
Ich hatte ein ähnliches Problem mit intellij IDEA . Sie können dies verwenden
VelocityEngine ve = new VelocityEngine();
Properties props = new Properties();
props.put("file.resource.loader.path", "/Users/Projects/Comparator/src/main/resources/");
ve.init(props);
Template t = ve.getTemplate("helloworld.vm");
VelocityContext context = new VelocityContext();
sie können versuchen, diesen Code hinzuzufügen:
VelocityEngine ve = new VelocityEngine();
String vmPath = request.getSession().getServletContext().getRealPath("${your dir}");
Properties p = new Properties();
p.setProperty("file.resource.loader.path", vmPath+"//");
ve.init(p);
Ich mache das und pass!
VelocityEngine velocityEngin = new VelocityEngine();
velocityEngin.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
velocityEngin.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
velocityEngin.init();
Template template = velocityEngin.getTemplate("nameOfTheTemplateFile.vtl");
sie können den obigen Code verwenden, um die Eigenschaften für die Geschwindigkeitsvorlage festzulegen. Sie können dann beim Initialisieren der Vorlage den Namen der Tempalte-Datei angeben und sie wird feststellen, ob sie im Klassenpfad vorhanden ist.
Alle oben genannten Klassen stammen aus dem Paket org.Apache.velocity *
Ich habe dieses Code-Snippet für zukünftige Verweise abgelegt. Das Codebeispiel wurde mit Apache Velocity Version 1.7 mit integriertem Jetty geschrieben.
Der Pfad für Velocity-Vorlagen befindet sich im Unterordner email_templates des Ressourcenordners.
Code-Snippet in Java (Snippets funktionieren sowohl in Eclipse als auch in einem Jar)
...
templateName = "/email_templates/byoa.tpl.vm"
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
Template t = ve.getTemplate(this.templateName);
VelocityContext velocityContext = new VelocityContext();
velocityContext.put("","") // put your template values here
StringWriter writer = new StringWriter();
t.merge(this.velocityContext, writer);
System.out.println(writer.toString()); // print the updated template as string
Für OSGI-Codeausschnitte .
final String TEMPLATE = "resources/template.vm // located in the resource folder
Thread current = Thread.currentThread();
ClassLoader oldLoader = current.getContextClassLoader();
try {
current.setContextClassLoader(TemplateHelper.class.getClassLoader()); // TemplateHelper is a class inside your jar file
Properties p = new Properties();
p.setProperty("resource.loader", "class");
p.setProperty("class.resource.loader.class", "org.Apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init( p );
VelocityEngine ve = new VelocityEngine();
Template template = Velocity.getTemplate( TEMPLATE );
VelocityContext context = new VelocityContext();
context.put("tc", obj);
StringWriter writer = new StringWriter();
template.merge( context, writer );
return writer.toString() ;
} catch(Exception e){
e.printStackTrace();
} finally {
current.setContextClassLoader(oldLoader);
}
Sie können Ihren Vorlagenordner auch unter src/main/resources anstelle von src/main/Java ablegen. Funktioniert für mich und es ist ein bevorzugter Ort, da Vorlagen keine Java-Quelle sind.
Ich war mit einem ähnlichen Problem konfrontiert. Ich habe die Mail-Templates für die Geschwindigkeitsmaschine in einen falschen Ordner kopiert. Da JavaMailSender und VelocityEngine als Ressourcen unter MailService deklariert sind, müssen die Vorlagen unter Ressourcenordner für das Projekt hinzugefügt werden.
Ich habe die Änderungen vorgenommen und es hat funktioniert. Legen Sie die Vorlagen als
src/main/resources/templates/<package>/sampleMail.vm
Bei Verwendung von Embedded Jetty sollte die Eigenschaft webapp.resource.loader.path mit einem Schrägstrich beginnen:
webapp.resource.loader.path=/templates
andernfalls werden Vorlagen in ../webapp/templates nicht gefunden