核心定義
| 路徑形式 | 稱呼 | 解析基準 | 適用場景 |
以 / 開頭 | Web 應用絕對路徑 / 相對 Context Root 路徑 | 當前 Web 應用根目錄 (Context Root) | JSP/Servlet 轉發、<form action>、<a href>、request.getRequestDispatcher() |
不以 / 開頭 | 相對路徑 | 當前請求 URL 所在目錄 | 頁面內資源引用(CSS/JS/圖片)、相對跳轉 |
| 以協議/域名/盤符開頭 | 系統絕對路徑 / 完整 URL | 文件系統根 / 協議根 | File 操作、外部連結、重定向 response.sendRedirect() |
關鍵區別:轉發 vs 重定向
- request.getRequestDispatcher("/a.jsp").forward():路徑相對 Context Root,
/ 代表應用根。
- response.sendRedirect("/a.jsp"):路徑相對域名根(Domain Root),
/ 代表 https://host:port/,不包含 Context Path。需手動拼接 request.getContextPath()。
- 頁面標籤:
<a href="/a.jsp"> 瀏覽器按域名根解析;<a href="${pageContext.request.contextPath}/a.jsp"> 才是應用根。
最佳實踐模板
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<!-- 頁面資源 -->
<link href="${ctx}/css/style.css" rel="stylesheet" />
<script src="${ctx}/js/main.js"></script>
<!-- 表單提交 -->
<form action="${ctx}/submit" method="post">
<!-- 頁面跳轉 -->
<a href="${ctx}/list">列表</a>
<!-- Servlet 轉發 -->
request.getRequestDispatcher("/WEB-INF/views/detail.jsp").forward(req, resp);
<!-- 重定向 -->
resp.sendRedirect(req.getContextPath() + "/list");
常見坑點速查
| 代碼 | 實際請求路徑 | 說明 |
response.sendRedirect("/app/user") | https://host:port/app/user | 若 Context Path 為 /myapp,會少一層 |
<a href="user/list"> (在 /myapp/admin/page.jsp) | https://host:port/myapp/admin/user/list | 相對當前目錄 |
request.getRequestDispatcher("user/list") | 錯誤:相對當前 Servlet 路徑 | 轉發必須用 / 開頭 |
總結口訣
轉發用絕對(/開頭),重定向加上下文;頁面引用用 EL 表達式,文件操作用系統絕對。