在WEB项目中使用basePath(jsp,js)
在JSP中,有相对路径和绝对路径。
相对路径容易理不清,而导致无法正确加载资源文件。
So,在做WEB项目时,建议都统一使用绝对路径。
- 一 JS中使用basePath
/*****basePath统一设置*******/
var curPath = window.document.location.href;
var pathName = window.document.location.pathname;
var basePath;
basePath = curPath.substring(0,curPath.indexOf(pathName)) + "/";
js中即可使用basePath + “URL”来使用了。
- 二 JSP 绝对路径
共用jsp文件:如 WEBROOT/common/basePath.jsp。
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<script type="text/javascript" src="<%=basePath %>js/path.js"></script>
<!-- 其他公共资源 -->
在每个jsp页面,引用公共页面
<%@include file="/common/common.jsp"%>
在jsp中,使用路径前加<%=basePath %>+url
<link rel="stylesheet" type="text/css" href="<%=basePath %>css/styles.css">
或设置当前jsp页面的默认地址为basePath
<head>
<base href="<%=basePath %>" />
<link rel="stylesheet" type="text/css" href="css/styles.css">
...