外部 .js 文件無法使用 JSP EL 表達式 ${pageContext.request.contextPath},需在 JS 中動態推導項目根路徑。
function getBasePath(){
const loc = window.location;
const path = loc.pathname; // /context/path/page.jsp
const ctx = path.split('/')[1]; // context
return loc.protocol + '//' + loc.host + '/' + ctx;
}
// 簡寫版(假設部署在根路徑或已知層級)
const basePath = (() => {
const parts = (window.location + '').split('/');
return parts[0] + '//' + parts[2] + '/' + parts[3]; // https://host/context
})();
<!-- JSP 頁面頭部 -->
<script>
window.APP_CONFIG = {
basePath: '${pageContext.request.contextPath}',
apiBase: '${pageContext.request.contextPath}/api'
};
</script>
<script src="static/js/app.js"></script>
外部 JS 直接讀取 window.APP_CONFIG.basePath,零解析、零耦合、易測試。
import.meta.env.BASE_URL (Vite) 或 __webpack_public_path__ 自動注入。<script>window.__BASE__ = '<%= BASE_URL %>';</script>。import api from './api',完全避免 basePath 問題。history 模式下 pathname 包含路由,解析需排除路由段。