page.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" errorPage="errorPage.jsp" %><!-- 指定错误处理的页面 --> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% int a = 1/0;/* 此页面出错了,就会转发到指定的错误处理页面 */ %> </body> </html>
errorPage.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isErrorPage="true"%><!-- 错误处理页面,只有设置了isErrorPage="true",才可以使用exception --> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1 style="color:orange;">您访问的页面出错了!!!</h1> <% exception.printStackTrace(); %> </body> </html>
如果单独为每个页面指定错误处理页面,这样太繁琐了。可以在web.xml文件中使用<erroe-page>元素为整个Web应用程序设置错误处理页面。
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Javaweb01</display-name> <error-page> <error-code>404</error-code> <location>/jsp/404.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/jsp/500.jsp</location> </error-page> </web-app>
page.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% int a = 1/0;/* 此页面出错了,变会转发到指定的错误处理页面 */ %> </body> </html>
404.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1 style="color:orange;">404错误处理页面</h1> </body> </html>
500.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1 style="color:orange;">500错误处理页面</h1> </body> </html>
访问:http://localhost:8080/Javaweb01/jsp/page1.jsp,由于不存在page1.jsp,响应状态码为404,因此会转发到404.jsp。
访问:http://localhost:8080/Javaweb01/jsp/page.jsp,由于page.jsp出错,响应状态码为500,因此会转发到500.jsp。