---
title: "TOMCAT自定义JNDI"
author: "orange5458"
date: "2011-05-19T23:44:39Z"
tags: []
categories: ["编程语言"]
slug: "tomcat-jndi"
draft: false
lastmod: "2011-05-19T23:44:39Z"
id: 1050889
url: "https://orange5458.iteye.com/blog/1050889"
---

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&lt;RefAddr&gt; 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

===================================================

&lt;?xml version='1.0' encoding='utf-8'?&gt;  
&lt;Context&gt;  
       
    &lt;Resource name="test/url"  
     auth="Container"  
     type="java.net.URL"  
     factory="com.siyuan.tomcat.jndi.MyURLFactory"  
     url="[file:///c:/test.properties"/]()&gt;  
          
&lt;/Context&gt;

 

jndiDiv.jsp

===================================================

&lt;jsp:directive.page import="javax.naming.InitialContext"/&gt;  
&lt;jsp:directive.page import="javax.naming.Context"/&gt;  
&lt;jsp:directive.page import="java.net.URL"/&gt;  
&lt;%  
 Context ctxt = new InitialContext();  
 Context envCtxt = (Context) ctxt.lookup("java:comp/env/");  
 URL url = (URL) envCtxt.lookup("test/url");  
%&gt;   
&lt;%=url %&gt;

 

3.运行结果

 

![](http://dl.iteye.com/upload/attachment/484403/68d59461-da03-32af-9aba-31ee0af8a806.jpg)

 

运行可能出错的原因有：

$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