zoukankan      html  css  js  c++  java
  • 转:getContextPath、getServletPath、getRequestURI的区别

    假定你的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("/")); 
    打印结果:F:Tomcat 6.0webapps ews est 

    -------------------------------------------------------------------

    1、request.getRequestURL()

    返回的是完整的url,包括Http协议,端口号,servlet名字和映射路径,但它不包含请求参数。
    2、request.getRequestURI()

    得到的是request URL的部分值,并且web容器没有decode过的

    3、request.getContextPath() 
    返回 the context of the request.

    4、request.getServletPath() 
    返回调用servlet部分的url.

    5、request.getQueryString() 
    返回url路径?后面的查询字符串

    示例:

    当前url:http://localhost:8080/CarsiLogCenter_new/idpstat.jsp?action=idp.sptopn

    request.getRequestURL() http://localhost:8080/CarsiLogCenter_new/idpstat.jsp
    request.getRequestURI()  /CarsiLogCenter_new/idpstat.jsp
    request.getContextPath() /CarsiLogCenter_new
    request.getServletPath() /idpstat.jsp

    request.getQueryString() action=idp.sptopn

    1、request.getScheme() 返回当前链接使用的协议;比如,一般应用返回http;SSL返回https;

    2、在程序中的应用如下:

    Java代码  收藏代码
    1. String path = request.getContextPath();  
    2.   
    3. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
    4.   
    5. <base href="<%=basePath%>">  

    3、复习一下request 的常用方法:

    request.getSchema()可以返回当前页面使用的协议,http 或是 https;

    request.getServerName()可以返回当前页面所在的服务器的名字;

    request.getServerPort()可以返回当前页面所在的服务器使用的端口,就是80;

    request.getContextPath()可以返回当前页面所在的应用的名字;

  • 相关阅读:
    八、Docker+RabbitMQ
    Spring.Net学习笔记一(IOC第一个实例)
    快速搞懂 SQL Server 的锁定和阻塞
    JQuery.Ajax()的data参数类型
    常用开源介绍
    AutoMapper简明教程(学习笔记)
    面向.Net程序员的前端优化
    --数组元素插入有两种方式
    JQuery源码分析-02正则表达式-RegExp-常用正则表达式
    关于ASP.NET MVC的Filter小记
  • 原文地址:https://www.cnblogs.com/zhangshitong/p/5197600.html
Copyright © 2011-2022 走看看