Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình

Cách tạo trang lỗi chung (common error page) bằng JSP

JSP cho phép bạn chỉ định Error Page cho mỗi JSP bằng page attribute. Bất cứ khi nào trang ném exception, JSP container tự động gọi error page.

Ví dụ chỉ định error page cho main.jsp. Để thiết lập error page, dùng 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>

Viết Error Handling JSP ShowError.jsp như sau. Lưu ý directive <%@ page isErrorPage = "true" %>. Directive này khiến JSP compiler sinh ra exception instance variable.

<%@ 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>

Truy cập main.jsp, bạn nhận được output như sau:

java.lang.RuntimeException: Error condition!!! ...... Opps... Sorry, an error occurred. Here is the exception stack trace: