zl程序教程

您现在的位置是:首页 >  后端

当前栏目

java中如何获取项目的路径

JAVA项目 如何 获取 路径
2023-09-14 09:06:16 时间

记录是为了更好的成长!

1、ssm项目中

1.以工程名为TEST为例:

(1)得到包含工程名的当前页面全路径:request.getRequestURI()
结果:/TEST/test.jsp
(2)得到工程名:request.getContextPath()
结果:/TEST
(3)得到当前页面所在目录下全名称:request.getServletPath()
结果:如果页面在jsp目录下 /TEST/jsp/test.jsp
(4)得到页面所在服务器的全路径:application.getRealPath(“页面.jsp”)
结果:D:\resin\webapps\TEST\test.jsp
(5)得到页面所在服务器的绝对路径:absPath=new java.io.File(application.getRealPath(request.getRequestURI())).getParent();
结果:D:\resin\webapps\TEST

2.在类中取得路径:

(1)类的绝对路径:Class.class.getClass().getResource(“/”).getPath()
结果:/D:/TEST/WebRoot/WEB-INF/classes/pack/
(2)得到工程的路径:System.getProperty(“user.dir”)
结果:D:\TEST

3.在Servlet中取得路径:

(1)得到工程目录:request.getSession().getServletContext().getRealPath(“”) 参数可具体到包名。
结果:E:\Tomcat\webapps\TEST
(2)得到IE地址栏地址:request.getRequestURL()
结果:http://localhost:8080/TEST/test
(3)得到相对地址:request.getRequestURI()
结果:/TEST/test

注释:当项目中的jsp页面有标签时,可以使用以下代码来获取根目录,以防项目名为空的时候报错:

 function getRootPath(){ 
return $("base").attr("href"); 
} 
var webpath=getRootPath(); //webpath就是目录路径变量 

2、springBoot项目中

1、在用户头像上传的功能实现时,为了获取目录路径,花了好些时间,简单记录一下:

String path = ClassUtils.getDefaultClassLoader().getResource("").getPath() //输出path: D:/java_project/manage/target/classes/

项目中图片上传的路径是 resources/static/img/headImg/ 中,路径可以这样写:

String path = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/img/headImg/";//输出
path:/D:/java_project/manage/target/classes/static/img/headImg/

2、还有一种写法,效果一样

//获取项目的根目录
File path = new File(ResourceUtils.getURL("classpath:").getPath());
System.out.println("path:"+path.getAbsolutePath());
//path:D:\java_project\manage\target\classes
        
//获取项目根目录下的某个文件夹,这里是  "static/img/headImg/"
File uploadpath = new File(path.getAbsolutePath(),"static/img/headImg/");
System.out.println("uploadpath:"+uploadpath.getAbsolutePath());
//uploadpath:D:\java_project\manage\target\classes\static\img\headImg
//也可以直接写成这样
String path = ResourceUtils.getURL("classpath:static/img/headImg/").getPath();
注意:ResourceUtils的这种写法在linux系统是无效,请注意推荐使用一下两种方式:
String rootPath = Class.class.getClass().getResource("/").getPath();
//D:\java_project\manage\target\classes\
String rootPath2 = ClassUtils.getDefaultClassLoader().getResource("").getPath();
//D:\java_project\manage\target\classes\