我有一个 Java EE 6 应用程序,我想在其中使用速度从模板生成邮件。我有一个 @Named bean 负责加载和填充特定模板。该项目是一个Web应用程序,所以我将模板放入WEB-INF/classes中(顺便说一句,这似乎相当难看,但我现在还没有找到更优雅的解决方案)并使用ClasspathResourceLoader来访问文件。配置如下:
Properties props = new Properties();
props.setProperty("resource.loader", "class");
props.setProperty("resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
VelocityEngine engine = new VelocityEngine(props);
VelocityContext context = new VelocityContext();
engine.init();
context.put("myObject", myObject);
Template template = engine.getTemplate("mail_template.vm");
StringWriter writer = new StringWriter();
template.merge(context, writer);
运行此代码会产生以下异常:
Caused by: java.lang.UnsupportedOperationException: Could not retrieve ServletContext from application attributes
at org.apache.velocity.runtime.log.ServletLogChute.init(ServletLogChute.java:73)
at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:157)
所以我需要将 ServletContext 交给速度引擎。但我的 bean 不知道该上下文,并且我不想使用 servlet 来发送邮件。前端是用 JSF 2.0 实现的,因此我可以访问 FacesContext.getCurrentInstance().getExternalContext().getContext(),将其转换为 ServletContext 并将其提供给引擎。然而上下文总是空的,我只是不知道如何让一切正常工作。每个提示/解决方案都受到高度赞赏:)
提前致谢,
亚历克斯
Velocity 可以在任何环境中运行,因此不需要 servlet。问题似乎与日志记录工具有关,其默认值取决于 servlet。
您可以使用NullLogChute
,或者,根据您的日志记录框架,选择一个实现的类LogChute
。例如,如果您使用公共日志记录,您需要CommonsLogLogChute http://velocity.apache.org/engine/devel/apidocs/org/apache/velocity/runtime/log/CommonsLogLogChute.html。如何设置:
要使用,首先设置commons-logging,然后通过将以下内容添加到velocity.properties中告诉Velocity使用此类进行日志记录:runtime.log.logsystem.class = org.apache.velocity.runtime.log.CommonsLogLogChute
您还可以设置此属性来指定应记录 Velocity 消息的日志/名称(下面的示例为默认值)。 runtime.log.logsystem.commons.logging.name = org.apache.velocity
因此,除了在velocity.properties中提供此设置之外,您还可以调用:
engine.setProperty("runtime.log.logsystem.class",
"org.apache.velocity.runtime.log.CommonsLogLogChute");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)