Java WEB项目中获取路径方法
程序员文章站
2022-04-29 18:57:18
...
java中获取路径
在java中获取当前项目的路径信息
public class BasePath {
public static void main(String[] args) throws URISyntaxException {
//1、来获得当前线程的ClassLoader相应的资源路径
String url = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath();
System.out.println("url:"+url);
//2、指定类的ClassLoader相应的资源路径
String url2 = BasePath.class.getClassLoader().getResource("").toURI().getPath();
System.out.println("url2:"+url2);
String url3 = ClassLoader.getSystemResource("").toURI().getPath();
System.out.println("url3:"+url3);
//4、当前类的详细地址,包含路径包名
String url4 = BasePath.class.getResource("").toURI().getPath();
System.out.println("url4:"+url4);
//5、当前类的根目录路径
String url5 = BasePath.class.getResource("/").toURI().getPath();
System.out.println("url5:"+url5);
//6、用户的当前工作目录(user.dir)
String url6 = System.getProperty("user.dir");
System.out.println("url6:"+url6);
//7、test.txt文件的路径为 项目名\src\test.txt;类TestPath所在包的第一级目录位于src目录下
String url7 = BasePath.class.getClassLoader().getResource("test.xml").toURI().getPath();
System.out.println("url7:"+url7);
}
}
执行结果如下:
url:/Users/project/build/classes/
url2:/Users/project/build/classes/
url3:/Users/project/build/build/classes/
url4:/Users/project/build/build/classes/com/learn/webProjectPath/
url5:/Users/project/build/build/classes/
url6:/Users/project/build
url7:/Users/project/build/build/classes/test.xml
servlet中获取路径
在servlet中获取项目路径
//1、根目录所对应的绝对路径:request.getServletPath()
String path1 = req.getServletPath();
System.out.println("path1:"+path1);
//2、文件的绝对路径:request.getSession().getServletContext().getRealPath(request.getRequestURI())
String path2 = req.getSession().getServletContext().getRealPath("/");
System.out.println("path2:"+path2);
//3、当前web应用的绝对路径:servletConfig.getServletContext().getRealPath("/")
String path3 = this.getServletConfig().getServletContext().getRealPath("/");
System.out.println("path3:"+path3);
执行结果如下:
path1:/path.action
path2:/Users/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/project/
path3:/Users/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/project/
jsp中获取路径
在jsp中获取项目路径
1、根目录所对应的绝对路径:request.getRequestURI();<BR>
<%=request.getRequestURI() %><BR>
2、当前web应用的绝对路径:application.getRealPath("/")<BR>
<%=application.getRealPath("/") %><BR>
3、获取当前所有项目的路径:request.getContextPath()<BR>
<%=request.getContextPath() %>
执行结果如下:
1、根目录所对应的绝对路径:request.getRequestURI();
/project/webProjectPath.jsp
2、当前web应用的绝对路径:application.getRealPath("/")
/Users/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/project/
3、获取当前所有项目的路径:request.getContextPath()
/project
上一篇: day11_前10天所用到的函数
下一篇: Java 项目中获取路径的方法小计