`
guomingzhang2008
  • 浏览: 157077 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

获取路径

    博客分类:
  • Java
阅读更多
获取路径的方法:


1、在java类中获取路径(com.zhanggm.Test.java)

// 方式1,通过classZLoader获取路径,参数必须是""。
this.getClass().getClassLoader().getResource("");
// 结果为:“file:/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/”,类型是java.net.URL。
this.getClass().getClassLoader().getResource("").getPath();
// 结果为:“/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/”,类型是String。

// 方式2,直接获取,参数可以随意指定,""获取当前类所在的路径、"/"获取根路径(即.../classes/)、"/xx/xx"、"/xx/xx/"等
this.getClass().getResource("").getPath();
// 结果为:“/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/com/zhanggm/”
this.getClass().getResource("/").getPath();
// 结果为:“/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/”
this.getClass().getResource("/com").getPath();
// 结果为:“/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/com”
this.getClass().getResource("/com/").getPath();
// 结果为:“/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/com/”
this.getClass().getResource("com").getPath();
// 结果为:“null”
this.getClass().getResource("com/").getPath();
// 结果为:“null”
this.getClass().getResource("/zhanggm").getPath();
// 结果为:“null”




2、通过 request 获取路径

String absolutePath= request.getRealPath("/");
// 结果为:“/D:/workspace/strutsTest/WebRoot/”,即获取是本地的绝对路径,WEB-INF所在的目录。这个路径可以用来存放文件。

String contextPath  = request.getContextPath();
// 结果为:“1、有项目名:"/xxPojectName",2、没有项目名:""”






3、在 struts2 中获取路径

String absolutePath = org.apache.struts2.ServletActionContext.getServletContext().getRealPath("/upload/");
// 结果为:“/D:/workspace/strutsTest/WebRoot/upload/”,即获取是本地的绝对路径。这个路径可以用来存放文件。




4、在 spring 中获取路径

/**
     * 获取应用的路径
     *
     * @return 应用的路径
     */
    protected String getAppPath() {
        org.springframework.web.context.WebApplicationContext webApplicationContext = org.springframework.web.context.ContextLoader.getCurrentWebApplicationContext();
        javax.servlet.ServletContext servletContext = webApplicationContext.getServletContext();
        return servletContext.getContextPath();
    }

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics