Velocity在哪里搜索模板?

我需要在Web应用程序中使用来自Java代码的Velocity(我将其用作邮件模板处理器)。

所以,我有一个标准代码:

VelocityEngine ve = new VelocityEngine (); try { ve.init (); Template t = ve.getTemplate (templatePath); ... } catch (Exception e) { throw new MailingException (e); } 

此代码始终抛出ResourceNotFoundException 。 我应该将模板放在web应用程序(WEB-INF?classpath?etc?)中,我应该如何指定路径(即我应该将什么作为templatePath传递)?

您需要首先通过调用Velocity.init() (在单例模型中使用)或VelocityEngine.init() (如果使用单独的实例)并传递适当的配置参数来初始化Velocity。 这些包括资源加载器配置 。

放置模板文件的位置取决于您选择的资源加载器 – 有文件,类路径,jar,url等资源加载器可用。

如果使用文件资源加载器,则模板路径应为绝对(目录/文件)路径。 但是,使用jar资源加载器,它不能是绝对路径(如果你的模板在jar中,那就是)。 对于模板中的链接也是如此,即如果您的模板之一包含另一个绝对路径,则jar资源加载器将无法加载它。

设置速度模板

我最终使用这个问题来解决我设置模板路径的问题。 我正在使用velocity来模板化html电子邮件。

您可以使用以下几种方法来说明如何设置模板路径。 它将属性’file.resource.loader.path’设置为绝对路径。 我为模板创建了一个目录,然后右键单击模板文件以获取完整路径(在Eclipse中)。 您使用该完整路径作为file.resource.loader.path属性的值。 我还添加了’runtime.log.logsystem.class’属性,并设置它,因为我收到了抱怨日志记录的exception。

UTILTY速度方法

 public static VelocityEngine getVelocityEngine(){ VelocityEngine ve = new VelocityEngine(); Properties props = new Properties(); // THIS PATH CAN BE HARDCODED BUT IDEALLY YOUD GET IT FROM A PROPERTIES FILE String path = "/absolute/path/to/templates/dir/on/your/machine"; props.put("file.resource.loader.path", path); props.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem"); ve.init(props); return ve; } public static String getHtmlByTemplateAndContext(String templateName, VelocityContext context){ VelocityEngine ve = getVelocityEngine(); Template template = ve.getTemplate(templateName); StringWriter writer = new StringWriter(); template.merge(context, writer ); System.out.println( writer.toString()); String velocityHtml = writer.toString(); return velocityHtml; } 

如何使用上面的代码,创建一个速度上下文,以提供有用的方法

以下是如何使用上述方法。 您只需指定模板文件的文件名,并创建一个简单的VelocityContext上下文来存储模板变量。

  VelocityContext context = new VelocityContext(); context.put("lastName", "Mavis"); context.put("firstName", "Roger"); context.put("email", "mrRogers@wmail.com"); context.put("title", "Mr."); String html = VelocityUtil.getHtmlByTemplateAndContext("email_template_2015_10_09.vm", context); 

示例模板HTML

可以访问变量(在我的例子中保存在文件email_template_2015_10_09.vm ):

 

Hello $firstName $lastName