我想使用 Tomcat 6.0 提供的标准资源工厂,它为我创建 javax.mail.Sessions 实例。如JNDI 资源 HOW-TO 教程中所述。
我的 META-INF/context.xml 看起来像:
<?xml version="1.0" encoding="UTF-8"?>
<Context reloadable="true">
<Resource name="mail/Session"
auth="Container"
type="javax.mail.Session"
mail.smtp.host="smtp.gmail.com"
mail.smtp.port="587"
mail.smtp.auth="true"
mail.smtp.user="someone@gmail.com"
mail.smtp.password="secretpassword"
mail.smtp.starttls.enable="true"/>
</Context>
我的 WEB-INF/web.xml 中有下一个资源引用,就在 </webapps> 之前。Web.xml 验证。我使用McDowell 的方式进行了验证。
<resource-ref>
<description>Resource reference to a factory for javax.mail.Session instances that may be used for sending electronic mail messages, preconfigured
to connect to the appropiate SMTP server.
</description>
<res-ref-name>mail/Session</res-ref-name>
<res-type>javax.mail.Session</res-type>
<res-auth>Container</res-auth>
</resource-ref>
我正在使用下一个代码片段访问我的 javax.mail.Session 对象。
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
Session session = (Session)envCtx.lookup("mail/Session");
System.out.println("HERE smtp.user: " + session.getProperty("mail.smtp.user"));
我在一个示例应用程序中对其进行了测试,它工作正常。不幸的是,当我将相同的代码移动到一个 struts 应用程序时,我在上面的打印语句中得到了 NULL。我在名为 mailer 的单例类中查找上下文(在我的 WEB-INF/classes 文件夹中定义),但是如果我在 Struts 动作类中查找上下文,我会遇到同样的问题。
我一直在想有什么不同的地方才能找到问题。我的 struts 应用程序 web.xml 比简单应用程序的 web.xml 更复杂。它具有安全约束、过滤器和 Struts Servlet 配置。我将 resource-ref 定位在 servlet 定义之前。似乎资源引用被忽略了。
我还有一个问题。如果我在 myapp/WEB-INF/lib 文件夹中有 javax.mail.Session 所需的 mailapi.jar,我会得到:
java.lang.NoClassDefFoundError: javax/mail/Authenticator
如果我把它放在 $CATALINA_HOME/lib 中就找到了。
有任何想法吗?我使用struts和hibernate。也许与此有关。
调试
我试图调试它,将调试属性放在上下文中
<Context reloadable="true" debug="99" ...
但我没有看到任何有趣的东西。
01-feb-2009 17:39:09 org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: contextInitialized()
01-feb-2009 17:39:09 org.apache.catalina.core.ApplicationContext log
INFO: SessionListener: contextInitialized()
01-feb-2009 17:39:09 org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: contextInitialized()
01-feb-2009 17:39:09 org.apache.catalina.core.ApplicationContext log
INFO: SessionListener: contextInitialized()
01-feb-2009 17:39:09 org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: contextInitialized()
01-feb-2009 17:39:09 org.apache.catalina.core.ApplicationContext log
我试过:
Session session = (Session) initCtx.lookup("java:comp/env/mail/Session");
代替:
Context envCtx = (Context) initCtx.lookup("java:comp/env");
Session session = (Session)envCtx.lookup("mail/Session");
但我仍然得到一个 NULL Session 对象。
部分解决方案
当我将 Resource 元素放在 $CATALINA_HOME/conf/context.xml 文件中时,它可以工作。