异常处理
当servlet出现异常时,servlet容器使用exception-type元素来找到与抛出的异常类型相匹配的配置
java
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);
}
}
xml
<!-- 配置异常处理的servlet -->
<servlet>
<servlet-name>ExceptionHandler</servlet-name>
<servlet-class>com.zhanghe.study.servlet.ExceptionHandler</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ExceptionHandler</servlet-name>
<url-pattern>/ExceptionHandler</url-pattern>
</servlet-mapping>
<!-- 配置哪些错误码会调用该异常处理类 -->
<error-page>
<error-code>404</error-code>
<location>/ExceptionHandler</location>
</error-page>
<!-- 配置哪些异常类型会调用该异常处理类 -->
<error-page>
<exception-type>java.lang.ArithmeticException</exception-type>
<location>/ExceptionHandler</location>
</error-page>
如果出现异常,会在请求域中设置相应的属性
可以使用request.getAttribute("")取出
java
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多平台发布