在html页面下写使用base标签,可以使所有地址都基于base地址。假设page1.html的绝对路径为:http://localhost:8080/A/B/page1.html,page2.html的绝对路径为:http://localhost:8080/A/B/C/page2.html。当设置<base href="http://localhost:8080/A/" />后,page1.html的路径可以写为:B/page1.html,page2.html的路径可以写为:B/C/page2.html。
在web目录下创建一个a目录,并在a目录下创建一个first.html,然后在a目录下创建一个b目录,并在b目录下创建一个second.html。实现由first.html页面跳转到second.html页面,再由second.html页面跳转到first.html页面。
一. 使用a标签进行页面跳转
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>First</title>
</head>
<body>
这是a目录下的first.html页面</br>
<a href="b/second.html">去往b目录下的second页面</a>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Second</title>
</head>
<body>
这是b目录下的second.html页面</br>
<a href="../first.html">去往a目录下的first页面</a>
</body>
</html>
二. 使用请求转发进行页面跳转
当使用请求转发方式进行页面跳转,将first.html页面跳转到second.html页面时,必须使用base标签,否则second.html页面无法跳转到first.html页面。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>First</title>
</head>
<body>
这是a目录下的first.html页面</br>
<a href="b/second.html">去往b目录下的second页面</a> </br>
<a href="http://localhost:8080/WebProject_war_exploded/forwardSecond">使用请求转发的方式去往b目录下的second页面</a>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Second</title>
<!-- base标签设置页面相对路径工作时参照的地址,href属性设置参照的地址值 -->
<base href="http://localhost:8080/WebProject_war_exploded/a/b/second.html">
</head>
<body>
这是b目录下的second.html页面</br>
<a href="../first.html">去往a目录下的first页面</a>
</body>
</html>
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ForwardSecond extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("经过了请求转发");
req.getRequestDispatcher("/a/b/second.html").forward(req,resp);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>ForwardSecond</servlet-name>
<servlet-class>TestServlet.ForwardSecond</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ForwardSecond</servlet-name>
<url-pattern>/forwardSecond</url-pattern>
</servlet-mapping>
</web-app>