文章目录
引例
目录结构
下面我们来举一个例子进行说明,首先列出目录结构
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
这是web下的index.html<br/>
<a href="./pages/login/login.html">pages下的login下的login.html</a><br/>
<a href="http://localhost:8080/MyTest_war_exploded/baseServlet">请求转发:pages/login/login.html</a>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
这是pages下的login下的login.html页面<br/>
<a href="../../index.html">返回首页</a>
</body>
</html>
演示
首先点击第一个没问题,进入后再点击返回主页确实跳转了
但是第二个就出错了,请求转发的
解释说明
所有相对路径在工作时候都会参照当前浏览器地址栏中的地址来进行跳转。
所以第一个返回首页地址为
http://localhost:8080/MyTest_war_exploded/pages/login/login.html/../../index.html
等价为http://localhost:8080/MyTest_war_exploded/index.html
因为../
是上级目录所以没一个这个…/就消除掉一个目录就得到了主页
而第二个地址为
http://localhost:8080/MyTest_war_exploded/baseServlet/../../index.html
消掉两个以后就剩下http://localhost:8080/index.html
当然会出错了
Base标签
在这种情况下运用base标签则显得很有意义,base 标签设置页面相对路径工作时参照的地址,在这以后所有相对路径在工作时候都会参照当前Base标签中的地址来进行跳转
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<base href="http://localhost:8080/MyTest_war_exploded/pages/login/login.html">
</head>
<body>
这是pages下的login下的login.html页面<br/>
<a href="../../index.html">返回首页</a>
</body>
</html>