假定你的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

最新文章

  1. c++函数模板作为类的成员函数,编译报错LNK2019的解决方法
  2. .NET LINQ 相等运算
  3. PreparedStatement
  4. JAVA中保留指定小数位方法
  5. web访问速度优化分析
  6. cocos2d-x 缓动曲线
  7. Spring(3.2.3) - Beans(5): 集合属性的注入
  8. .Net用js实现aspx页面删除TextBox输入框的前后空格
  9. C语言复习--实现栈
  10. jQuery遍历table
  11. 《精通android网络开发》--HTTP数据通信
  12. [NewLife.XCode]对象字典缓存(百万军中取敌首级)
  13. [C# 设计模式] Adapter - 适配器模式(两种)
  14. java爬知乎问题的所有回答
  15. mysql 正则表达式判断是否数字
  16. Spring Boot读取配置的几种方式
  17. Python项目代码结构
  18. 简单实现"回车!=提交"(去除表单的回车即提交)
  19. 转:C#常用的集合类型(ArrayList类、Stack类、Queue类、Hashtable类、Sort)
  20. PCM转MP3工具的封装

热门文章

  1. 转载关于reset vector 和 exception vector
  2. homebrew的安装与使用
  3. HDOJ5877(dfs序+离散化+树状数组)
  4. SpringMvc访问Controller去掉do
  5. 今天去python官网下载包安装的时候的问题记录
  6. PTA 银行排队问题之单队列多窗口服务(25 分)
  7. Python模块详解以及import本质,获得文件当前路径os.path.abspath,获得文件的父目录os.path.dirname,放到系统变量的第一位sys.path.insert(0,x)
  8. tp5 快速接入扫码支付
  9. 如何安装pip
  10. mysql核心参数优化