• java中如何获取项目的路径


     
    记录是为了更好的成长!
     

    1、ssm项目中

    以工程名为TEST为例: 

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

    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:TomcatwebappsTEST 
    (2)得到IE地址栏地址:request.getRequestURL() 
    结果:http://localhost:8080/TEST/test 
    (3)得到相对地址:request.getRequestURI() 
    结果:/TEST/test
    注释:当项目中的jsp页面有<base href="<%=request.getContextPath()%>/">标签时,可以使用以下代码来获取根目录,以防项目名为空的时候报错:
     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_projectmanage	argetclasses
            
    //获取项目根目录下的某个文件夹,这里是  "static/img/headImg/"
    File uploadpath = new File(path.getAbsolutePath(),"static/img/headImg/");
    System.out.println("uploadpath:"+uploadpath.getAbsolutePath());
    //uploadpath:D:java_projectmanage	argetclassesstaticimgheadImg

    //也可以直接写成这样
    String path =
    ResourceUtils.getURL("classpath:static/img/headImg/").getPath();
    注意:ResourceUtils的这种写法在linux系统是无效,请注意

    推荐使用一下两种方式:
    String rootPath = Class.class.getClass().getResource("/").getPath();
    //
    D:java_projectmanage argetclasses

    String rootPath2 = ClassUtils.getDefaultClassLoader().getResource("").getPath();
    //D:java_projectmanage argetclasses

     

     
     
     
    以上内容代表个人观点,仅供参考,不喜勿喷。。。
  • 相关阅读:
    Python之while循环
    Python之分支语句
    Python之变量
    Python开挂的吧!
    xshell 连接 ubuntu 16.04报错
    js中的script标签
    javascript中的事件学习总结
    【JAVAWEB学习笔记】04_JavaScript
    【JAVAWEB学习笔记】03_JavaScript
    【JAVAWEB学习笔记】02_HTML&CSS
  • 原文地址:https://www.cnblogs.com/newbest/p/9146698.html
Copyright © 2020-2023  润新知