JAVA获取WEBROOT物理路径的方法

2019-03-26 06:50|来源: 网路

在WEB-INF/web.xml中配置context-param,name为webAppRootKey,value为webapp.root

<web-app version="2.4"    
    xmlns="http://java.sun.com/xml/ns/j2ee"    
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee     
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">    
  <context-param>    
        <param-name>webAppRootKey</param-name>    
        <param-value>webapp.root</param-value>    
  </context-param>    
  <listener>    
        <listener-class>com.656463.ApplicationListener</listener-class>    
 </listener>    
         
</web-app>


然后通过Listener,或者Filter,或者Servlet获取到物理路径

String webAppRootKey = getServletContext().getRealPath("/");


对webAppRootKey对应的webapp.root赋值,并写入到System Properties系统属性中,java程序中可通过System.getProperty("webapp.root")来获得WebRoot的物理路径

import javax.servlet.ServletContextEvent;    
     
import org.springframework.web.context.ContextLoaderListener;    
     
public class ApplicationListener extends ContextLoaderListener {    
     
    public void contextDestroyed(ServletContextEvent sce) {    
        // TODO Auto-generated method stub    
     
    }    
     
    public void contextInitialized(ServletContextEvent sce) {    
        // TODO Auto-generated method stub    
        String webAppRootKey = sce.getServletContext().getRealPath("/");    
        System.setProperty("webapp.root" , webAppRootKey);    
        String path =System.getProperty("webapp.root");    
        System.out.println("path="+path);    
    }    
     
}


整理于网络


相关问答

更多