JAVA取得WEBROOT物理路径

WEB -INF/web .xml 中 , 创建一个webAppRootKey的param, 指定一个值(默认为webapp.root)作为键值, 然后通过Listener , 或者Filter , 或者Servlet 执行String webAppRootKey = getServletContext().getRealPath("/"); 并将webAppRootKey对应的webapp.root 分别作为Key , Value写到System Properties系统属性中。之后在程序中通过System.getProperty("webapp.root")来获得WebRoot的物理路径

 

web.xml<?xml version="1.0" encoding="UTF-8"?>

<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.joshua.ApplicationListener</listener-class>  
 </listener>  
      
</web-app>

 

ApplicationListener.java

package com.joshua;  
  
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);  
    }  
  
}  
 

你可能感兴趣的:(java,Web,xml,servlet,sun)