Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        6年前关闭。
                                                                                            
                
        
我需要从运行在Tomcat 6上的Web应用程序访问FTP服务器。我想使用JNDI来做到这一点。

如何使用JNDI在Tomcat中配置此FTP连接?
我必须写什么web.xmlcontext.xml来配置资源?然后如何从Java源代码访问此连接?

最佳答案

从这篇文章:http://codelevain.wordpress.com/2010/12/18/url-as-jndi-resource/

像这样在您的context.xml中定义您的FTP URL:

 <Resource name="url/SomeService" auth="Container"
 type="java.net.URL"
 factory="com.mycompany.common.URLFactory"
 url="ftp://ftpserver/folder" />


提供com.mycompany.common.URLFactory实现,并确保结果类可用于Tomcat:

import java.net.URL;
import java.util.Hashtable;
import javax.naming.*;
import javax.naming.spi.ObjectFactory;

public class URLFactory implements ObjectFactory {
 public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception {
 Reference ref = (Reference) obj;
 String urlString =  (String) ref.get("url").getContent();
 return new URL(urlString);
 }
}


在web.xml中创建参考

<resource-ref>
 <res-ref-name>
   url/SomeService
 </res-ref-name>
 <res-type>
   java.net.URL
 </res-type>
 <res-auth>
   Container
 </res-auth>
</resource-ref>


然后在您的代码中通过执行JNDI查找来获取FTP URL:

InitialContext context = new InitialContext();
URL url = (URL) context.lookup("java:comp/env/url/SomeService");

10-06 12:53
查看更多