获取JAVA[WEB]项目相关路径的几种方法

在jsp和class文件中调用的相对路径不同。

在jsp里,根目录是WebRoot;在class文件中,根目录是WebRoot/WEB-INF/classes;当然你也可以用System.getProperty("user.dir")获取你工程的绝对路径。

如下为在Jsp,Servlet,Java中详细获得路径的方法!以Java Web工程名为MyPath为例。

jsp中获取路径

(1) 得到包含工程名的当前页面全路径:request.getRequestURI();

结果:/MyPath/jsp/pathpage.jsp

(2) 得到工程名:request.getContextPath();

结果:/MyPath

(3) 得到当前页面所在目录下全名称:request.getServletPath();

结果:如果页面在jsp目录下 /jsp/pathpage.jsp

(4) 得到页面所在服务器的全路径:application.getRealPath("jsp/pathpage.jsp");

结果:F:\apache-tomcat-6.0.35\webapps\MyPath\jsp\pathpage.jsp

(5) 得到页面所在服务器的绝对路径:String absPath = new java.io.File(application.getRealPath(request.getServletPath())).getParent();

结果:F:\apache-tomcat-6.0.35\webapps\MyPath\jsp

(6) 得到项目的访问路径:request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";

结果:http://localhost:8080/MyPath/ 

在类中获取路径

(1) 得到class文件的存放路径:String path = Class.class.getClass().getResource("/").getPath();

结果:/F:/WorkSpace/MyPath/WebRoot/WEB-INF/classes/

//str会得到这个函数所在类的路径
String str = path.toString();

//截去一些前面1个无用的字符
str = str.substring(1,str.length());

//将%20换成空格(如果文件夹的名称带有空格的话,会在取得的字符串上变成%20)
str = str.replaceAll("%20", " ");

//查找"WEB-INF"在该字符串的位置
int num = str.indexOf("WEB-INF");

//截取即可
str = str.substring(0, num+"WEB-INF".length());

最后结果为:F:/WorkSpace/MyPath/WebRoot/WEB-INF

(2) 得到工程的路径:System.getProperty("user.dir");

结果:F:\WorkSpace\MyPath

(3) 得到class的绝对路径:PathJava.class.getClass().getResource("").getPath();

结果:/F:/WorkSpace/MyPath/WebRoot/WEB-INF/classes/com/path/test/

通过ClassLoader来加载getResource()时不需要加 "/" 因为source是从main开始的;

Thread.currentThread().getContextClassLoader().getResource("main/test/test.txt").getPath();

通过Class.getResource()来加载文件时需要加“/”。

在Servlet中获取路径

(1) 得到工程目录:request.getSession().getServletContext().getRealPath("") 参数可具体到包名。

结果:F:\apache-tomcat-6.0.35\webapps\MyPath

(2) 得到IE地址栏地址:request.getRequestURL() 

结果:http://localhost:8080/MyPath/jsp

(3) 得到相对地址:request.getRequestURI() 

结果:/MyPath/jsp

在JUnit中获取路径

如果你是Maven项目,想在Junit 单元测试过程中加载src/main/resources目录下资源文件,可以在pom.xml中添加如下内容:

<build>
    <testResources>
        <testResource>
            <directory>${project.basedir}/src/test/resources</directory>
        </testResource>
        <testResource>
            <directory>${project.basedir}/src/main/resources</directory>
        </testResource>
    </testResources>
</build>

 

posted @ 2022-09-30 17:50  残城碎梦  阅读(1756)  评论(0编辑  收藏  举报