1.编写一个Spring获取Bean的工具类(记得让Spring扫描该类)

@Component
public class SpringUtil implements ApplicationContextAware{

   private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringUtil.applicationContext == null) {
            SpringUtil.applicationContext = applicationContext;
        }
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //根据name
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    //根据类型
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}

2.编写Struts2的过滤器,我写的这个主要是为了从FTP文件服务器下载文件

@Component
public class MyFileFilter implements Filter{

   @Autowired
   private FtpClientTemplate ftpClientTemplate;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,ServletException   {
	HttpServletRequest req = (HttpServletRequest) request;
	HttpServletResponse resp = (HttpServletResponse) response;
	HttpSession session = req.getSession();
	String url = req.getRequestURI();
    	if (url.contains("/upload/users/") && session.getAttribute("login_user") != null) {
    	   ftpClientTemplate.downloadFile(resp, "", url);
    	} else {
    	   chain.doFilter(request, response);
    	}
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    	if (ftpClientTemplate == null) {
    	   ftpClientTemplate = (FtpClientTemplate)SpringUtil.getBean(FtpClientTemplate.class);
    	}
    }

    @Override
    public void destroy() {}

}

3.在web.xml配置该过滤器,应该写在struts2的过滤器之前

<filter>
   <filter-name>file</filter-name>
   <filter-class>com.carter.filter.MyFileFilter</filter-class>
</filter>
<filter-mapping>
   <filter-name>file</filter-name>
   <url-pattern>/upload/*</url-pattern>
</filter-mapping>
06-10 19:17