读文档学习tomcat JNDI的配置:
JNDI:java Naming and Directory Interface(java命名与目录接口),它为java应用程序提供命名和目录访问服务的API。
JNDI中的Naming,就是将Java对象一某个名称的形式绑定到一个容器环境中,以后调用容器环境的查找方法又可以查找出某个名称所绑定的Java对象。
打开:D:/apache-tomcat-7.0.6/webapps/docs/jndi-resources-howto.html
下面是一个配置JavaMail sessions的例子:
0. Introduction
在许多的web应用中,发邮件使我们系统必须的功能,JavaMail给我们提供了简单的已经封转好了的API,但是客服端发送邮件,它就必须知道很多的环境配置信息细节。
tomcat有一个标准的resource factory,它可以帮我们传创建java.mail.session(这个类保存环境配置信息)的实例,resource factory会帮助我们配置好连接smtp服务器的各种细节信息。
好处:
In this way, the application is totally insulated from changes in the email server configuration environment - it simply asks for, and receives, a preconfigured session whenever needed.
百度文库:
包含了大量的命名和目录服务,使用通用接口来访问不同种类的服务;
可以同时连接到多个命名或目录服务上;
建立起逻辑关联,允许把名称同Java对象或资源关联起来,而不必知道对象或资源的物理ID。
JNDI程序包:
javax.naming :命名操作;
javax.naming.directory :目录操作;
javax.naming.event :在命名目录服务器 中请求事件通知;
javax.naming.ldap :提供LDAP支持;
javax.naming.spi :允许动态插入不同实现。
利用JNDI的命名与服务功能来满足企业级API对命名与服务的访问,诸如EJB、JMS、JDBC 2.0以及IIOP上的RMI通过JNDI来使用CORBA的命名服务。
1. Declare Your Resource Requirements
要完成JNDI的配置就要修改/WEB-INF/web.xml
一个典型的实例如下:
<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 appropriate
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>
程序中的调用的代码为:(o,文档中写的很详细啊)
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");//java:comp/env
naming context that is the root of
all provided resource factories.
Session session = (Session) envCtx.lookup("mail/Session");
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(request.getParameter("from")));
InternetAddress to[] = new InternetAddress[1];
to[0] = new InternetAddress(request.getParameter("to"));
message.setRecipients(Message.RecipientType.TO, to);
message.setSubject(request.getParameter("subject"));
message.setContent(request.getParameter("content"), "text/plain");
Transport.send(message);
下面的代码可以帮助理解:
Attribute attr = directory.getAttributes(personName).get("email");
String email = (String)attr.get();
通过使用JNDI让客户使用对象的名称或属性来查找对象:
foxes = directory.search("o=Wiz,c=US", "sn=Fox", controls);
通过使用JNDI来查找诸如打印机、数据库这样的对象,查找打印机的例子:
Printer printer = (Printer)namespace.lookup(printerName);
printer.print(document);
3. Configure Tomcat's Resource Factory
可以在我们的工程目录META-INF目录下建context.xml,添加代码:
<Context ...>
...
<Resource name="mail/Session" auth="Container"
type="javax.mail.Session"
mail.smtp.host="localhost"/>
...
</Context>
4. Install the JavaMail libraries
当然要想实现发送邮件的功能,当然要下载JavaMail封转的API,mail.jar,下载地址为:
http://www.oracle.com/technetwork/java/index-138643.html
5. Restart Tomcat
示例代码: