Apache FTPServer 集成到Spring(S2SH) WEB项目中

Apache FTPServer可以集成到自己的WEB项目中,单独用也非常不错。

测试了一下和Spring WEB项目结合。留下代码如下:

[xml]

<listener>
<listener-class>com.strong.utils.ftpservice.FtpServerListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/classes/com/strong/spring/applicationFTP.xml
</param-value>
</context-param>

[/xml]

FtpServerListener.java

[java]
package ibmer.info.ftp;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.ftpserver.impl.DefaultFtpServer;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class FtpServerListener implements ServletContextListener {
public void contextDestroyed(ServletContextEvent contextEvent) {
System.out.println("Stopping FtpServer");
DefaultFtpServer server = (DefaultFtpServer) contextEvent
.getServletContext().getAttribute("FTPSERVER_CONTEXT_NAME");
if (server != null) {
server.stop();
contextEvent.getServletContext().removeAttribute(
"FTPSERVER_CONTEXT_NAME");
System.out.println("FtpServer stopped");
} else {
System.out.println("No running FtpServer found");
}
}

public void contextInitialized(ServletContextEvent contextEvent) {
    System.out.println(&quot;Starting FtpServer&quot;);
    WebApplicationContext ctx = WebApplicationContextUtils
            .getWebApplicationContext(contextEvent.getServletContext());
    DefaultFtpServer server = (DefaultFtpServer) ctx.getBean(&quot;myServer&quot;);
    contextEvent.getServletContext().setAttribute(&quot;FTPSERVER_CONTEXT_NAME&quot;,
            server);
    try {
        server.start();
        System.out.println(&quot;FtpServer started&quot;);
    } catch (Exception e) {
        throw new RuntimeException(&quot;Failed to start FtpServer&quot;, e);
    }
}

}
[/java]

application-FTP.xml

[xml]
<server xmlns="http://mina.apache.org/ftpserver/spring/v1&quot; xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation="http://mina.apache.org/ftpserver/spring/v1 http://mina.apache.org/ftpserver/ftpserver-1.0.xsd&quot;
id="StrongFTP" max-logins="500" anon-enabled="false" max-anon-logins="123" max-login-failures="124" login-failure-delay="125">
<listeners>
<nio-listener name="default" port="2222" implicit-ssl="false" idle-timeout="60" local-address="127.0.0.1" />
</listeners>
<file-user-manager file="users.properties" encrypt-passwords="true" />
</server>
[/xml]

在web.xml中调用application-FTP.xml或者在spring中import这个xml。

[xml]
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param>
[/xml]

具体参数就不解释了,大家看文档。

原理是做一个ServletContextListener,tomcat启动时开始ftp服务器,结束时停止ftp服务器。