Apache FTPServer 集成到Spring WEB项目中

Apache FTPServer好东西,可以集成到自己的WEB项目中,单独用也非常不错。大家有兴趣可以研究一下,测试了一下和Spring WEB项目结合。留下代码如下:

 

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>

 

FtpServerListener.java

package com.strong.utils.ftpservice;

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

import org.apache.ftpserver.FtpServer;
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 sce) {
    System.out.println("Stopping FtpServer");
    DefaultFtpServer server = (DefaultFtpServer) sce.getServletContext().getAttribute(FtpConstants.FTPSERVER_CONTEXT_NAME);
    if (server != null) {
      server.stop();
      sce.getServletContext().removeAttribute("FTPSERVER_CONTEXT_NAME");
      System.out.println("FtpServer stopped");
    } else {
      System.out.println("No running FtpServer found");
    }
  }

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

 

applicationFTP.xml

<server xmlns="http://mina.apache.org/ftpserver/spring/v1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://mina.apache.org/ftpserver/spring/v1 http://mina.apache.org/ftpserver/ftpserver-1.0.xsd"
  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>

 具体参数就不解释了,大家看文档。大概的做法是做一个ServletContextListener,tomcat启动时开始ftp服务器,结束时停止ftp服务器。

你可能感兴趣的:(apache,spring,应用服务器,Web,Mina)