【发布时间】:2010-11-13 23:33:07
【问题描述】:
我有一个 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 并将其提供给引擎。然而上下文总是空的,我只是不知道如何让一切正常工作。每个提示/解决方案都受到高度赞赏:)
提前致谢, 亚历克斯
【问题讨论】:
标签: java templates jsf classloader velocity