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