JavaWeb - base标签的运用

引例

目录结构

下面我们来举一个例子进行说明,首先列出目录结构
在这里插入图片描述

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>

猜你喜欢

转载自blog.csdn.net/solitudi/article/details/107238359