【问题标题】:How to load a velocity template into an EJB to be used as a mail template如何将速度模板加载到 EJB 中以用作邮件模板
【发布时间】: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


    【解决方案1】:

    Velocity 可以在任何环境中运行,因此不需要 servlet。似乎问题与日志记录工具有关,其默认值取决于 servlet。

    您可以使用NullLogChute,或者根据您的日志框架,选择一个实现LogChute 的类。例如,如果您使用公共日志记录,则需要CommonsLogLogChute。如何设置:

    要使用,首先设置 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");
    

    【讨论】:

    • 谢谢 Bozho,它为我解决了日志记录问题。现在我遇到了(再次)找不到我的模板的问题。如上所述,我使用了 ClasspathResourceLoader,将我的模板放在一个 jar 中,如下所述:velocity.apache.org/engine/releases/velocity-1.5/… 那么,你也有解决这个问题的方法吗?谢谢!亚历克斯
    • 发现问题,属性叫'class.resource.loader.class'而不是'resource.loader.class'
    猜你喜欢
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多