首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> JSP 程式設計 >> 關於JSP

JSP 錯誤頁面配置完整指南:errorPage 與 isErrorPage 實作範例

     編輯:關於JSP

    核心機制

    JSP 提供聲明式錯誤處理:發生異常的頁面指定 errorPage,錯誤處理頁面宣告 isErrorPage="true" 即可獲得隱含物件 exception。

    一、錯誤處理頁面:errorPage.jsp

    <%@ page isErrorPage="true" contentType="text/html; charset=UTF-8" %>
    <html>
    <head><title>系統錯誤</title></head>
    <body>
        <h2 style="color:red">系統發生錯誤!</h2>
        <p><strong>錯誤訊息:</strong> ${exception.message} </p>
        <p><strong>堆疊追蹤:</strong></p>
        <pre>${exception.stackTrace}</pre>
        <p><a href="javascript:history.back()">返回上一頁</a></p>
    </body>
    </html>
    

    二、業務頁面:指定 errorPage

    <%@ page errorPage="errorPage.jsp" contentType="text/html; charset=UTF-8" %>
    <html>
    <body>
    <%
        // 模擬業務邏輯異常
        boolean errorCondition = true;
        if (errorCondition) {
            throw new RuntimeException("資料庫連線失敗:Connection refused");
        }
    %>
    <p>正常內容(不會顯示)</p>
    </body>
    </html>
    

    三、web.xml 全域錯誤頁面(補充)

    <error-page>
        <exception-type>java.lang.Exception</exception-type>
        <location>/errorPage.jsp</location>
    </error-page>
    <error-page>
        <error-code>404</error-code>
        <location>/404.jsp</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/500.jsp</location>
    </error-page>
    

    四、關鍵注意事項

    • isErrorPage="true" 的頁面才能使用 exception 隱含物件,否則編譯報錯。
    • errorPage 支援相對/絕對路徑,建議以 /errorPage.jsp 絕對路徑避免路徑解析問題。
    • 錯誤頁面本身發生異常會導致容器顯示預設錯誤頁,錯誤頁面邏輯務必極簡單、健壯。
    • 生產環境錯誤頁面應隱藏堆疊追蹤,僅顯示友善訊息,避免洩露系統細節。

    五、進階:自定義異常處理 Servlet(替代方案)

    @WebServlet("/GlobalExceptionHandler")
    public class GlobalExceptionHandler extends HttpServlet {
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
            Throwable ex = (Throwable) req.getAttribute("javax.servlet.error.exception");
            Integer code = (Integer) req.getAttribute("javax.servlet.error.status_code");
            // 統一記錄日誌、回傳 JSON/頁面
        }
    }
    

    web.xml 註冊:<error-page><location>/GlobalExceptionHandler</location></error-page>

    1. 上一篇文章:
    2. 下一篇文章:
    Copyright © 程式碼之家 All Rights Reserved