java web 路径获取_JavaWeb项目中各种路径的获取

以工程名为/DemoWeb为例:

访问的jsp为: http://localhost:8080/DemoWeb/test/index.jsp

1 JSP中获得当前应用的相对路径和绝对路径

(1)得到工程名:request.getContextPath()

结果:/DemoWeb

(2)得到包含工程名的当前页面全路径:request.getRequestURI()

结果:/DemoWeb/test/testpath.jsp

(3)得到IE地址栏地址:request.getRequestURL()

结果:http://localhost:8080/DemoWeb/test/testpath.jsp

(4)得到当前页面所在目录下全名称:request.getServletPath()

结果:/test/testpath.jsp

(5)得到页面所在服务器的全路径(实际的路径):application.getRealPath("testpath.jsp")

结果:D:\Develop Files\apache-tomcat-5.5.15\apache-tomcat-5.5.15\webapps\DemoWeb\testpath.jsp

D:\Develop Files\apache-tomcat-5.5.15\apache-tomcat-5.5.15为tomcat的安装路径

(6) Web应用中有各种获取path或URI,URL的方法,假设网页访问地址:

http://localhost:8080/tradeload/TestServlet

Web应用context: /tradeload

request.getContextPath()= /tradeload

request.getScheme()+ "://" + request.getServerName() + ":" + request.getServerPort()= http://localhost:8080

request.getRequestURL() = http://localhost:8080/tradeload/TestServlet

request.getRequestURI() = /tradeload/TestServlet

request.getPathInfo()= nullrequest.getServletPath()= /TestServlet

getServletContext().getRealPath('/') = C:\server\glassfish\domains\domain1\applications\j2ee-modules\tradeload\

2.java 的Class中获得相对路径,绝对路径的方法

(1)类的绝对路径:

System.out.println(TestPath.class.getResource("/").getPath());

结果:/E:/workspace/workspace_tcc/DemoWeb/WebRoot/WEB-INF/classes/

System.out.println(TestPath.class.getResource(""));

结果:file:/E:/workspace/workspace_tcc/DemoWeb/WebRoot/WEB-INF/classes/demo1/

(2)得到工程的路径:System.getProperty("user.dir")

结果:E:\workspace\workspace_tcc\DemoWeb

(3)得到项目部署的绝对路径:

//获取运行项目名称

WebApplicationContext wac =ContextLoader.getCurrentWebApplicationContext();

ServletContext sc=wac.getServletContext();

String projectName= sc.getContextPath();

//获取运行项目路径 即tomcat下的项目路径(默认情况下)

//tomcat conf server.xml配置文件若有配置项目路径,则是该docBase的路径

WebApplicationContext webApplicationContext =ContextLoader.getCurrentWebApplicationContext();

ServletContext servletContext=webApplicationContext.getServletContext();

String projectPath=servletContext.getRealPath("/").replace("\\", "/");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值