如何使用 JSP 建立一個通用錯誤頁面?
使用 page 屬性,JSP 會為你提供針對每個 JSP 指定錯誤頁面的選項。每當頁面引發異常時,JSP 容器會自動呼叫錯誤頁面。
以下是針對main.jsp指定錯誤頁面的示例。若要設定錯誤頁面,請使用<%@ page errorPage = "xxx" %>指令。
<%@ page errorPage = "ShowError.jsp" %> <html> <head> <title>Error Handling Example</title> </head> <body> <% // Throw an exception to invoke the error page int x = 1; if (x == 1) { throw new RuntimeException("Error condition!!!"); } %> </body> </html>
接下來我們將編寫一個錯誤處理 JSP ShowError.jsp(如下所示)。請注意,錯誤處理頁面包括指令<%@ page isErrorPage = "true" %>。此指令將導致 JSP 編譯器生成異常例項變數。
<%@ page isErrorPage = "true" %> <html> <head> <title>Show Error Page</title> </head> <body> <h1>Opps...</h1> <p>Sorry, an error occurred.</p> <p>Here is the exception stack trace: </p> <pre><% exception.printStackTrace(response.getWriter()); %></pre> </body> </html>
訪問 **main.jsp**,你將接收類似於以下內容的輸出−
java.lang.RuntimeException: Error condition!!! ...... Opps... Sorry, an error occurred. Here is the exception stack trace:
廣告