getContextPath、getServletPath、getRequestURI,getRealPath的区别
假定你的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
最新文章
- c++函数模板作为类的成员函数,编译报错LNK2019的解决方法
- .NET LINQ 相等运算
- PreparedStatement
- JAVA中保留指定小数位方法
- web访问速度优化分析
- cocos2d-x 缓动曲线
- Spring(3.2.3) - Beans(5): 集合属性的注入
- .Net用js实现aspx页面删除TextBox输入框的前后空格
- C语言复习--实现栈
- jQuery遍历table
- 《精通android网络开发》--HTTP数据通信
- [NewLife.XCode]对象字典缓存(百万军中取敌首级)
- [C# 设计模式] Adapter - 适配器模式(两种)
- java爬知乎问题的所有回答
- mysql 正则表达式判断是否数字
- Spring Boot读取配置的几种方式
- Python项目代码结构
- 简单实现";回车!=提交";(去除表单的回车即提交)
- 转:C#常用的集合类型(ArrayList类、Stack类、Queue类、Hashtable类、Sort)
- PCM转MP3工具的封装
热门文章
- 转载关于reset vector 和 exception vector
- homebrew的安装与使用
- HDOJ5877(dfs序+离散化+树状数组)
- SpringMvc访问Controller去掉do
- 今天去python官网下载包安装的时候的问题记录
- PTA 银行排队问题之单队列多窗口服务(25 分)
- Python模块详解以及import本质,获得文件当前路径os.path.abspath,获得文件的父目录os.path.dirname,放到系统变量的第一位sys.path.insert(0,x)
- tp5 快速接入扫码支付
- 如何安装pip
- mysql核心参数优化