在獨立 `.js` 檔案中撰寫 ${isLogin} 等 EL 表達式,瀏覽器收到的是原始字串而非解析後的值。
| 階段 | 執行環境 | 處理內容 |
|---|---|---|
| 1. 伺服端 | Servlet Container (Tomcat 等) | 解析 JSP/HTML 中的 EL 表達式,輸出純文字/HTML/JS |
| 2. 傳輸 | HTTP Response | 發送已渲染完成的靜態資源 |
| 3. 客戶端 | 瀏覽器 JS 引擎 | 執行純 JS 代碼,無法解析 EL |
結論:`.js` 檔案預設不經過伺服端模板引擎處理,EL 表達式無效。
<!-- list.jsp -->
<script>
// 在 JSP 中定義全域配置物件
window.APP_CONFIG = {
isLogin: "${isLogin}", // EL 在此處被解析
userId: "${user.id}",
basePath: "${pageContext.request.contextPath}"
};
</script>
<script src="/static/js/main.js"></script>
// main.js (獨立 JS 檔)
$(function() {
// 直接讀取全域配置
var isLogin = window.APP_CONFIG.isLogin;
if (isLogin === '1') {
typeShow(".congra");
} else if (isLogin === '10001') {
typeShow(".randToContent");
setTimeout(function() { window.location.href = randUrl; }, 3000);
}
});
<!-- web.xml 設定 .js 由 JSP 處理器解析 -->
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
缺點:破壞靜態資源快取、增加伺服器負擔、前後端耦合、建置流程複雜化。
<body data-is-login="${isLogin}" data-user-id="${user.id}">...</body>
// JS 讀取
var isLogin = document.body.dataset.isLogin; // HTML5 dataset API
// 或
var isLogin = $('body').data('is-login'); // jQuery
// 後端提供配置端點
GET /api/config
Response: { "isLogin": "1", "userId": 123, "basePath": "/app" }
// 前端啟動時請求
fetch('/api/config').then(r => r.json()).then(config => {
window.APP_CONFIG = config;
initApp();
});
var x = "${val}";,否則 JS 語法錯誤(如值含空格、特殊字元)<c:out>)DefinePlugin / import.meta.env 注入編譯時常數