当前位置: 代码迷 >> Web前端 >> java web工程中怎么获取webroot 路径
  详细解决方案

java web工程中怎么获取webroot 路径

热度:743   发布时间:2013-01-04 10:04:17.0
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");