Apache FTPServer 集成到Spring WEB项目中

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

 

web.xml

  
    com.strong.utils.ftpservice.FtpServerListener
  
  
    contextConfigLocation
     
      /WEB-INF/classes/com/strong/spring/applicationFTP.xml
    
  

 

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


  
    
  
  

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

你可能感兴趣的:(Spring)