JSP 中的頁面物件有什麼用?能否舉個例子。


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:

更新於: 30-07-2019

157 次訪問

開啟你的 職業生涯

完成該課程以獲得認證

開始
廣告
© . All rights reserved.