当servlet出现异常时,servlet容器使用exception-type元素来找到与抛出的异常类型相匹配的配置
public class ExceptionHandler extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Throwable throwable = (Throwable) req.getAttribute("javax.servlet.error.exception");
Integer code = (Integer) req.getAttribute("javax.servlet.error.status_code");
String message = (String) req.getAttribute("javax.servlet.error.message");
System.out.println("=========");
System.out.println(throwable);
System.out.println("=========");
System.out.println(code);
System.out.println("=========");
System.out.println(message);
}
}
<servlet>
<servlet-name>ExceptionHandlerservlet-name>
<servlet-class>com.zhanghe.study.servlet.ExceptionHandlerservlet-class>
servlet>
<servlet-mapping>
<servlet-name>ExceptionHandlerservlet-name>
<url-pattern>/ExceptionHandlerurl-pattern>
servlet-mapping>
<error-page>
<error-code>404error-code>
<location>/ExceptionHandlerlocation>
error-page>
<error-page>
<exception-type>java.lang.ArithmeticExceptionexception-type>
<location>/ExceptionHandlerlocation>
error-page>
如果出现异常,会在请求域中设置相应的属性
可以使用request.getAttribute("")取出
javax.servlet.error.status_code //错误码,Integer类型
javax.servlet.error.exception_type // 异常类型,Class类型
javax.servlet.error.message //异常信息,String类型
javax.servlet.error.request_uri //出现异常的uri地址,String类型
javax.servlet.error.exception //异常,Throwable类型
javax.servlet.error.servlet_name //servlet名称,String类型
本文由 mdnice 多平台发布