在 JSP 開發中,正確獲取專案的絕對路徑(Base Path)是構建資源連結、重定向及 AJAX 請求的基礎。若處理不當,極易導致資源載入失敗或路徑錯誤。本文將詳細介紹如何在 JSP 中動態構建絕對路徑,並提供可直接套用的程式碼範例。
透過 HttpServletRequest 物件,我們可以取得協議、伺服器名稱、連接埠及專案上下文路徑,組合出完整的基礎 URL。這種方式不依賴硬編碼,支援專案部署在不同環境(開發、測試、生產)時自動適配。
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":"
+ request.getServerPort()
+ path + "/";
%>
<head>
<base href="<%=basePath%>">
<link rel="stylesheet" href="css/style.css">
<script src="js/main.js"></script>
</head>
設定 <base> 標籤後,所有相對路徑資源將自動解析為絕對路徑。
<form action="<%=basePath%>user/login" method="post">...</form>
<a href="<%=basePath%>product/detail?id=1001">商品詳情</a>
<script>
var basePath = '<%=basePath%>';
// AJAX 請求範例
$.ajax({
url: basePath + 'api/data',
method: 'GET',
success: function(res) { console.log(res); }
});
</script>
為避免重複程式碼,建議將上述邏輯提取至 common/basePath.jsp:
<%@ page contentType="text/html;charset=UTF-8" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":"
+ request.getServerPort()
+ path + "/";
pageContext.setAttribute("basePath", basePath);
%>
其他頁面只需引入:
<%@ include file="/common/basePath.jsp" %>
<base href="${basePath}">
getServerPort() 可能返回內部埠而非 80/443。需配置 X-Forwarded-* 標頭並在 JSP 中優先讀取。getScheme() 會自動返回 "http" 或 "https",無需手動判斷。採用 request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/" 為標準模式,配合 <base> 標籤或 EL 表達式 ${basePath},能徹底解決 JSP 專案中的路徑問題,提升程式碼可維護性與環境遷移彈性。