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()可以返回当前页面所在的应用的名字;

  • 相关阅读:
    POJ2186(有向图缩点)
    POJ3352(连通分量缩点)
    POJ1523(割点所确定的连用分量数目,tarjan算法原理理解)
    POJ3694(求割边)
    POJ3177(无向图变双连通图)
    POJ1144(割点入门题)
    maven(1)-linux环境下安装maven
    linux(10)-linux环境下jdk配置自定义环境变量/etc/profile.d以及卸载自带openjdk
    ant(1)-linux环境下安装ant
    apache(2)-linux环境下apache-httpd编译安装
  • 原文地址:https://www.cnblogs.com/zhangshitong/p/5197600.html
Copyright © 2011-2022 走看看