JSP为您提供了一个使用页面属性为每个JSP指定错误页面的选项。每当页面抛出异常时,JSP容器都会自动调用错误页面。
以下是为main.jsp指定错误页面的示例。要设置错误页面,请使用<%@页面errorPage =“ xxx”%>指令。
<%@ page errorPage = "ShowError.jsp" %>
<html>
<head>
<title>Error Handling Example</title>
</head>
<body>
<%
//引发异常以调用错误页面
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: