JSP中request.*中的路径值

浅浅的花香味﹌ 2021-09-23 00:00 398阅读 0赞

JSP中request.*中的路径值

request.getContextPath()

今天终于明白了jsp中的request.getContextPath()是怎么回事了。

request.getContextPath() 返回站点的根目录

request.getRealpath(“/“)得到的是实际的物理路径,也就是你的项目所在服务器中的路径

request.getScheme() 等到的是协议名称,默认是http

request.getServerName() 得到的是在服务器的配置文件中配置的服务器名称 比如:localhost .baidu.com 等等

request.getServerPort() 得到的是服务器的配置文件中配置的端口号 比如 8080等等

有一个例子来说明吧

有个web应用程序 名称就是demo

  1. <%
  2. String basePath = request.getScheme() + "://"
  3. + request.getServerName() + ":" + request.getServerPort();
  4. String path = request.getScheme() + "://" + request.getServerName()
  5. + ":" + request.getServerPort() + request.getContextPath()
  6. + "/";
  7. String filePath=path+"resources/";
  8. session.setAttribute("path", path);
  9. session.setAttribute("basePath", basePath);
  10. session.setAttribute("filePath", filePath);
  11. %>

以上这段代码是 demo中每一个jsp页面中都包含的一段代码

其中 request.getContextPath() = /demo

basePath = http://localhost:8080

path = http://localhost:8080/demo/

filePath = http://localhost:8080/demo/resources/

用法:

如果在jsp界面中引用resources/images/文件夹下面的图片icon.png写法如下:

  1. <img src="${filePath }images/icon.png" />

或者

  1. <img src="${path}resources/images/icon.png" />

同理 如果在resources/css/文件夹下引用style.css写法如下:

  1. <link href="${filePath} css/style.css" rel="stylesheet" type="text/css" />
  2. <link href="${path} resources/css/style.css" rel="stylesheet" type="text/css" />

OK!

代码片

  1. <%
  2. String basePath = request.getScheme() + "://"
  3. + request.getServerName() + ":" + request.getServerPort();
  4. String path = request.getScheme() + "://" + request.getServerName()
  5. + ":" + request.getServerPort() + request.getContextPath()
  6. + "/";
  7. String filePath=path+"resources/";
  8. session.setAttribute("path", path);
  9. session.setAttribute("basePath", basePath);
  10. session.setAttribute("filePath", filePath);
  11. %>

参考文章:https://www.cnblogs.com/yuan1225/p/3219629.html

发表评论

表情:
评论列表 (有 0 条评论,398人围观)

还没有评论,来说两句吧...

相关阅读

    相关 request问题

    一个非常怪异的问题,帮忙看下,我在action 的execute()方法中,我拿到了request值.并打印出来,也就是调用了system.out.println();然后我在