JSP 開發過程中常遇到各類執行期錯誤,本文整理高頻錯誤、根因分析與解決方案,助您快速排查。
原因: JNDI 資料源名稱未正確綁定,或 META-INF/context.xml 設定錯誤(<Context> 標籤名稱拼寫、資源名稱不符)。
解決:
context.xml 中 <Resource name="jdbc/YourDS" .../> 的 name 屬性。web.xml <resource-ref> 的 <res-ref-name>jdbc/YourDS</res-ref-name> 一致。<Context>,不可寫成其他名稱。現象: response.sendRedirect() 後仍有輸出,或緩衝區已衝刷又嘗試清空。
解決:
sendRedirect 後立即 return,避免後續程式碼輸出。<%@ page buffer="10kb" %>(預設 8kb)。out.print、空白字元、include 等輸出行為。原因: 同時 import java.sql.* 與 import java.util.*,兩個套件皆有 Date 類別,編譯器無法判斷使用哪一個。
解決:
java.util.Date today = new java.util.Date();現象: 資料庫預設 UTF-8,JSP 插入資料出現亂碼。
解決:
jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=utf-8new String(request.getParameter("param").getBytes("ISO-8859-1"), "UTF-8")(僅適用 GET 參數)。request.setCharacterEncoding("UTF-8"),資料庫、表、欄位皆設 utf8mb4。現象: 表單提交「保存」等中文按鈕值,後端比對失敗。
解決:
<%@ page pageEncoding="UTF-8" contentType="text/html;charset=UTF-8" %> + request.setCharacterEncoding("UTF-8") + response.setCharacterEncoding("UTF-8")。<input type="hidden" name="action" id="hide">,JS 設值 document.getElementById('hide').value = 1(1=保存, 2=重置...)。錯誤: <textarea value="<%= bean.getContent() %>"></textarea>(不顯示)。
正確: <textarea><%= bean.getContent() %></textarea>。textarea 的內容由標籤內文決定,而非 value 屬性。