JAVA (WEB)获取路径的方法

在web项目中jsp、java、servlet均需要获取路径。

1、在java中

(1)获取当前java文件的classpath路径(所有编译成class的文件存放的总路径)

this.getClass().getClassLoader().getResource("").getRealPath();       

(2)获取当前java文件编译成的class文件的路径

this.getClass().getResource("").getRealPath();         //显示路径到当前包开始

this.getClass().getResource("/").getRealPath();        //显示路径到当前src文件夹下

(3)获取当前classpath的绝对uri

Thread.currentThread().getContextClassLoader().getResource("").getPath()

2、在jsp中

在jsp页面中(假设当前项目名称为Path   jsp名称为test.jsp):

request.contextPath();   //获取当前jsp的工程项目全名称(/Path/)

request.getServletPath();     //获取当前jsp所在的相对路径(如果jsp在top着个文件夹中   /Path/top/test.jsp)

request.getRequestURI();    //获取当前jsp所在的绝对路径(/Test/test.jsp)

3、在servlet中

request.getSession().getServletContext().getRealPath("");  //F:\java\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\aaaaaaaa\

request.getRequestURL();  // http://localhost:8080/aaaaaaaa/Servlet1

request.getRequestURI();   //  /aaaaaaaa/Servlet1

猜你喜欢

转载自blog.csdn.net/qq_39429962/article/details/82822438