Tomcat:通过 JNDI 使用 FTP 连接

Bob*_*Bob 2 java ftp tomcat jndi

我需要从在 Tomcat 6 上运行的 Web 应用程序访问 FTP 服务器。我想使用 JNDI 来执行此操作。

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

Gui*_*rre 5

来自这篇文章: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" />
Run Code Online (Sandbox Code Playgroud)

提供 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);
 }
}
Run Code Online (Sandbox Code Playgroud)

在 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>
Run Code Online (Sandbox Code Playgroud)

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

InitialContext context = new InitialContext();
URL url = (URL) context.lookup("java:comp/env/url/SomeService");
Run Code Online (Sandbox Code Playgroud)