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


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

    在jsp里,根目录是WebRoot 在class文件中,根目录是WebRoot/WEB-INF/classes 当然你也可以用System.getProperty("user.dir")获取你工程的绝对路径。
    如下为在Jsp,Servlet,Java中详细获得路径的方法!以Java Web工程名为MyPath为例:
    1.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.35webappsMyPathjsppathpage.jsp
    (5)得到页面所在服务器的绝对路径:String absPath = new java.io.File(application.getRealPath(request.getServletPath())).getParent();
    结果:F:apache-tomcat-6.0.35webappsMyPathjsp
    (6)得到项目的访问路径:request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
    结果:http://localhost:8080/MyPath/


    2.在类中取得路径

    (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:WorkSpaceMyPath

    (3)得到class的绝对路径:PathJava.class.getClass().getResource("").getPath();
    结果:/F:/WorkSpace/MyPath/WebRoot/WEB-INF/classes/com/path/test/

    3.在Servlet中取得路径

    (1)得到工程目录:request.getSession().getServletContext().getRealPath("") 参数可具体到包名。
    结果:F:apache-tomcat-6.0.35webappsMyPath
    (2)得到IE地址栏地址:request.getRequestURL()
    结果:http://localhost:8080/MyPath/jsp
    (3)得到相对地址:request.getRequestURI()
    结果:/MyPath/jsp

  • 相关阅读:
    [转]十步完全理解SQL
    [转]Java日期时间使用总结
    [转]Mybatis出现:无效的列类型: 1111 错误
    [转]java.lang.OutOfMemoryError: PermGen space及其解决方法
    [转]Spring3核心技术之事务管理机制
    [转]Spring的事务管理难点剖析(1):DAO和事务管理的牵绊
    设计模式之装饰模式
    进程通信
    设计模式之备忘录模式
    设计模式之单例模式
  • 原文地址:https://www.cnblogs.com/cnjavahome/p/4275249.html
Copyright © 2020-2023  润新知