简单的bean利用spring得到服务器上的路径
利用spring中的ServletContextAware 接口获得ServletContext ,从而获得服务器上下文路径
程序片段:
package com.ahtec.oa.service.impl;import java.io.File;import java.io.IOException;import javax.servlet.ServletContext;import org.apache.commons.io.FileUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;import org.springframework.web.context.ServletContextAware;/** * @author Wu */@Componentpublic class AutoRunServiceImpl implements ServletContextAware { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); private ServletContext servletContext; public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } public void deletePdcaZipFile() { logger.debug("start deletePdcaZipFile ..."); String pdcaDeleteFileLocation = ""; try { String fileLocation = "files\\pdca\"; String ctxDir = this.servletContext.getRealPath(String.valueOf(File.separatorChar)); if (!ctxDir.endsWith(String.valueOf(File.separatorChar))) { ctxDir = ctxDir + File.separatorChar; } pdcaDeleteFileLocation = ctxDir + fileLocation; FileUtils.deleteDirectory(new File(pdcaDeleteFileLocation)); logger.debug("has deleted : '{}' all files!", pdcaDeleteFileLocation); logger.debug("end deletePdcaZipFile..."); } catch (IOException e) { logger.debug("do not find pdcaDeleteFileLocation: {}", pdcaDeleteFileLocation); } logger.debug("============================================================"); }}