当在JSP的page指令中设置errorPage="url"就可以设置处理异常事件的JSP文件。如可以这样写:
<%@ page errorPage="error.jsp" %>
这样的话,当页面中出现异常的时候,就会自动跳转到错误处理页面。但是要注意,
只有当正常打开页面,然后在页面中出现异常的时候才会跳转到错误处理页面,如果页面本身有语法错误而出现了编译错误,是不会跳转的!
例:index.jsp
<%@ page contentType="text/html; charset=GB2312" language="java" errorPage="error.jsp"%><html><head><title>lifecycle</title></head><body><%!private int initVar = 0;private int serviceVar = 0;private int destroyVar = 0;public void jspInit() { initVar ++; }public void jspDestroy() { destroyVar ++; }%><%serviceVar ++;String content1="初始化次数:" + initVar;String content2="响应客户请求次数:" + serviceVar;String content3="销毁次数:" + destroyVar;out.println("<h1>hahaha</h1>");if(serviceVar==5){String info = getServletInfo();throw new Exception("Exception in:" + info);}%><h1><%=content1%></h1><h1><%=content2%></h1><h1><%=content3%></h1><!--this is some funny words.--></body></html>
下面的是error.jsp
<%@ page contentType="text/html; charset=GB2312" language="java" isErrorPage="true"%><html><head><title>error</title></head><body>this is the error page.</body></html>