[关闭]
@Dukebf 2017-07-11T16:04:25.000000Z 字数 758 阅读 852

jsp学习之路径问题

jsp


0x00 基本知识介绍

jsp中request对象是javax.servlet.http.HttpServletRequest类的实例,可以获取到客户端请求的情况,如:

方法 作用
request.getContxtPath() 获取当前访问路径
request.getScheme() 获取访问协议
request.getServerName() 获取访问地址
request.getServerPort() 获取端口

其他具体的,可以查看其他教程,传送门

0x01 路径问题

Tomcat 上跑多个工程,一般会用工程名进行区分 URL。
比如URL是:http://localhost/工程名 /home/index.jsp
这时需要加上 <%=request.getContextPath() %>动态获取工程名,如:

  1. <link rel="stylesheet" type="text/css" href="<%=request.getContextPath()/static/style.css">

但每次都要重复写<%=request.getContextPath() %>,那就很累人了。所以,可以在 header.jsp 或者每个文件的开头顶部,加入下面的内容:

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

在文件中就可以直接用<link rel="stylesheet" type="text/css" href="static/style.css">

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注