JSP ให้คุณเลือก Error Page สำหรับแต่ละ JSP โดยใช้ Page Attribute ทุกครั้งที่หน้าโยน Exception เครื่อง JSP จะเรียก Error Page อัตโนมัติ
ตัวอย่างต่อไปนี้ระบุ Error Page สำหรับ main.jsp เพื่อตั้งค่า Error Page ให้ใช้ Directive <%@ 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>
เราจะเขียน Error Handling JSP หนึ่งคือ ShowError.jsp ด้านล่าง สังเกตว่าหน้าจัดการข้อผิดพลาดมี Directive <%@ page isErrorPage = "true" %> Directive นี้ทำให้ JSP Compiler สร้าง Instance Variable Exception
<%@ page isErrorPage = "true" %> <html> <head> <title>Show Error Page</title> </head> <body> <h1>Oops...</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!!! ...... Oops... Sorry, an error occurred. Here is the exception stack trace: