在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.35\webapps\MyPath\jsp\pathpage.jsp
(5)得到页面所在服务器的绝对路径:String absPath = new
java.io.File(application.getRealPath(request.getServletPath())).getParent();
结果:F:\apache-tomcat-6.0.35\webapps\MyPath\jsp
(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:\WorkSpace\MyPath

(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.35\webapps\MyPath
(2)得到IE地址栏地址:request.getRequestURL()

结果:http://localhost:8080/MyPath/jsp
(3)得到相对地址:request.getRequestURI()
结果:/MyPath/jsp

最新文章

  1. 01_Swift2基础之Swift简介+创建
  2. Linux 下 scp 传输文件脚本
  3. [Android]The connection to adb is down, and a severe error has occured.
  4. [转]About the security content of iOS 8
  5. poj1681 高斯消元
  6. CentOS 安装 ceph 单机版(luminous版本)
  7. Python 入门基础17 --加密、表格、xml模块
  8. QT中QLineEdit的editingFinished()信号在按下回车时会触发两次的解决办法
  9. Spring boot注解使用
  10. pH计
  11. NetworkX 使用(二)
  12. Jump Game II leetcode java
  13. [Pytorch]Pytorch加载预训练模型(转)
  14. C#开发微信公众化平台
  15. 将CString写入到本地文件中
  16. Java开发进阶技能(附文章引用链接)
  17. Hadoop Ecosystem related ports
  18. Mixamo Fuse10分钟创建角色
  19. 《springcloud 四》服务保护机制
  20. 使用setInterval函数改变网页背景的颜色

热门文章

  1. ORA-20000 ORU-10027 buffer overflow limit of 2000 bytes
  2. cocos2d3.x在android下屏蔽多点触控
  3. 使用sublime编写c/c++ 总结
  4. (实用篇)php官方微信接口大全(微信支付、微信红包、微信摇一摇、微信小店)
  5. css布局列表,自适应
  6. js操作做GridView
  7. 各种报错各种坑 webpack让我在学习的过程中一度想要放弃
  8. Linux makefile 教程 非常详细,且易懂
  9. backbone学习总结(一)
  10. List的Capacity