转自:https://blog.csdn.net/bao19901210/article/details/23370407
1.需要在web.xml中配置相关信息
1 <!-- 默认的错误处理页面 --> 2 <error-page> 3 <error-code>403</error-code> 4 <location>/403.html</location> 5 </error-page> 6 <error-page> 7 <error-code>404</error-code> 8 <location>/404.html</location> 9 </error-page> 10 <!-- 仅仅在调试的时候注视掉,在正式部署的时候不能注释 --> 11 <!-- 这样配置也是可以的,表示发生500错误的时候,转到500.jsp页面处理。 --> 12 <error-page> 13 <error-code>500</error-code> 14 <location>/500.html</location> 15 </error-page> 16 17 <!-- 这样的配置表示如果jsp页面或者servlet发生java.lang.Exception类型(当然包含子类)的异常就会转到500.jsp页面处理。 --> 18 <error-page> 19 <exception-type>java.lang.Exception</exception-type> 20 <location>/500.jsp</location> 21 </error-page> 22 23 <error-page> 24 <exception-type>java.lang.Throwable</exception-type> 25 <location>/500.jsp</location> 26 </error-page> 27 <!-- 28 当error-code和exception-type都配置时,exception-type配置的页面优先级高 29 及出现500错误,发生异常Exception时会跳转到500.jsp 30 -->
2.如果配置是html时,不用另做配置
如果配置是Jsp时,需要把isErrorPage设置为true,
及<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isErrorPage="true"%>
3.获取异常信息及输出
1 <%@page import="java.io.PrintStream"%> 2 <%@page import="java.io.ByteArrayOutputStream"%> 3 <%@ include file="WEB-INF/views/includes/tags.jsp"%> 4 <%@ page language="java" contentType="text/html; charset=UTF-8" 5 pageEncoding="UTF-8" isErrorPage="true"%> 6 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 7 <html> 8 <head> 9 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 10 <title>500 服务器内部错误</title> 11 </head> 12 <body> 13 <div class="ui-alert-panel"> 14 <h1>服务器内部错误</h1> 15 <p>处理您的请求时发生错误!请确认您通过正确途径操作。</p> 16 </div> 17 <div style="display:none;"> 18 <% //此处输出异常信息 19 exception.printStackTrace(); 20 21 ByteArrayOutputStream ostr = new ByteArrayOutputStream(); 22 exception.printStackTrace(new PrintStream(ostr)); 23 out.print(ostr); 24 %> 25 </div> 26 </body> 27 </html>