1.简介
TOMCAT默认提供的JNDI配置支持对象有限,比较常用的有DataSource,JavaBean等,
有时无法满足用户的需求 。比如需要在构建对象的构造函数中传递参数等情况。
2. 示例
使用TOMCAT的JNDI配置URL资源
MyURLFactory.java
===================================================
package com.siyuan.tomcat.jndi;
import java.net.URL;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;
public class MyURLFactory implements ObjectFactory {
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
Hashtable environment) throws Exception {
URL url = null;
Reference ref = (Reference) obj;
Enumeration<RefAddr> cfgAttrs = ref.getAll();
while (cfgAttrs.hasMoreElements()) {
RefAddr cfgAttr = cfgAttrs.nextElement();
String attrName = cfgAttr.getType();
String attrValue = (String) cfgAttr.getContent();
if ("url".equals(attrName)) {
url = new URL(attrValue);
}
}
return url;
}
}
Context.xml
===================================================
<?xml version='1.0' encoding='utf-8'?>
<Context>
<Resource name="test/url"
auth="Container"
type="java.net.URL"
factory="com.siyuan.tomcat.jndi.MyURLFactory"
url="file:///c:/test.properties"/>
</Context>
jndiDiv.jsp
===================================================
<jsp:directive.page import="javax.naming.InitialContext"/>
<jsp:directive.page import="javax.naming.Context"/>
<jsp:directive.page import="java.net.URL"/>
<%
Context ctxt = new InitialContext();
Context envCtxt = (Context) ctxt.lookup("java:comp/env/");
URL url = (URL) envCtxt.lookup("test/url");
%>
<%=url %>
3.运行结果
运行可能出错的原因有:
$TOMCAT_HOME$\conf\Catalina\localhost\$APP_NAME$.xml 中的内容没有与$APP_INSTALL_DIR$\META-INF\context.xml同步。
解决方法:
将$APP_NAME$.xml删除后重启APP。
4.参考资料
$TOMCAT_HOME$\webapps\docs\jndi-resources-howto.html