博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
getContextPath、getServletPath、getRequestURI,getRealPath的区别
阅读量:6922 次
发布时间:2019-06-27

本文共 1283 字,大约阅读时间需要 4 分钟。

 

假定你的web application 项目名称为news,你在浏览器中输入请求路径: http://localhost:8080/news/main/list.jsp 

 

则执行下面向行代码后打印出如下结果: 

1、 System.out.println(request.getContextPath()); //可返回站点的根路径。也就是项目的名字 
打印结果:/news 

2、System.out.println(request.getServletPath()); 

打印结果:/main/list.jsp 

3、 System.out.println(request.getRequestURI()); 

打印结果:/news/main/list.jsp 

 

4、 System.out.println(request.getRealPath("/")); 

      request.getRealPath("/")已经不建议使用。

getRealPath();

返回一个字符串,包含一个给定的真实路径。

struts2中:

ServletContext ctx=ServletActionContext.getServletContext();

String path=ctx.getRealPath("/");

String path1=ctx.getRealPath("/files/view.jsp");

输出:path为D:\Javasoftware\apache-tomcat-7.0.70\apache-tomcat-7.0.70\webapps\struts2-1\

         path1为D:\Javasoftware\apache-tomcat-7.0.70\apache-tomcat-7.0.70\webapps\struts2-1\files\view.jsp

\files\view.jsp这部分就是虚拟路径

D:\Javasoftware\apache-tomcat-7.0.70\apache-tomcat-7.0.70\webapps\struts2-1\  为项目的绝对路径

 servlet中:

 

private ServletConfig  config;

public void init(ServletConfig config) throws ServletException {

this.config=config;}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

ServletContext ctx=config.getServletContext();

String temp=ctx.getRealPath("/");
}

打印结果:F:\Tomcat 6.0\webapps\news\test 

 

注:

URI=contextPath+servletPath

转载地址:http://kmujl.baihongyu.com/

你可能感兴趣的文章
查询公司服务器类型
查看>>
我的友情链接
查看>>
(一)hadoop系列之__XP环境下搭建linux虚拟机
查看>>
我的友情链接
查看>>
LAMP+LVS+KEEPALIVED(五)
查看>>
uboot的作用和启动方式
查看>>
1.2关系数据库
查看>>
SpringCloud
查看>>
RHEL主机安全检查机制: TCP Wrappers、Xinetd
查看>>
泛型编程之类模板
查看>>
salt安装
查看>>
linux运维基础1
查看>>
Hyper-V Server虚拟机移动性
查看>>
Visual Studio 2014 预览版 CTP3 发布了!可以下载
查看>>
protoc 在linux下的安装
查看>>
jq上百个input 做提交不能为空的验证
查看>>
网络篇
查看>>
全面详解Linux日志管理技巧
查看>>
翻译连载 | 第 11 章:融会贯通 -《JavaScript轻量级函数式编程》 |《你不知道的JS》姊妹篇...
查看>>
去中心化访问HTTP服务集群
查看>>