类似于ServletActionContext.getServletContext().getRealPath
可以获得webroot/下的路径。
但我是用CXF写的webservice  直接调用的接口。然后直接进入service层,并没用通过servlet或者action。我想知道,这样怎么才能获得项目的路径。  

解决方案 »

  1.   


    没经过servlet哪来的request...
      

  2.   


    /**
     * 获得工程的classpath根目录
     * @return String
     */
    public String getClasspath() {
    try {
    return Class.forName("随便一个class").getResource("/").getPath();
    } catch (Exception e) {
    e.printStackTrace();
    }
    return "";
    }/**
     * 获得工程的WebRoot根目录
     * @return String
     */
    public String getWebRootPath() {
    try {
    String classpath = getClasspath();// classes 目录的物理路径
    String webInfoPath = new File(classpath).getParent();// WEB-INF 目录的物理路径
    return new File(webInfoPath).getParent();// WebRoot 目录的物理路径
    } catch (Exception e) {
    e.printStackTrace();
    }
    return "";
    }
      

  3.   


    多谢回答,不过我Class.forName("随便一个class")时出错,是我填的类名出错了吗?
    比如有个HelloWord类,就Class.forName("HelloWord")。我报错了java.lang.ClassNotFoundException。求助。
      

  4.   

    那就
    new File(".").getAbsoluteFile().getParent()
      

  5.   

    哥...
    包名要写全呀,比如:com.test.entity.HelloWord
      

  6.   


    非常感谢,不过能不能获得项目TOMCAT路径啊,项目部署后不可能还有workspace啊。