java web工程中如何获取webroot 路径

话不多说,直接上代码


在web.xml中加入

    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>webapp.root</param-value>
    </context-param>

    <listener>
        <listener-class>cn.csdb.carbon.Listener</listener-class>
    </listener>





Listener 类

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
* Created with IntelliJ IDEA.
* User: tsaowe
* Date: 12-11-28
* Time: 上午10:33
*/
public class Listener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        String webroot = servletContextEvent.getServletContext().getRealPath("/");
        System.setProperty("webapp.root", webroot);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    }
}



在代码中获取

String webroot =  System.getProperty("webapp.root");














你可能感兴趣的:(Java Web)