异常处理
当servlet出现异常时,servlet容器使用exception-type元素来找到与抛出的异常类型相匹配的配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| 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); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <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(“”)取出
1 2 3 4 5 6
| javax.servlet.error.status_code javax.servlet.error.exception_type javax.servlet.error.message javax.servlet.error.request_uri javax.servlet.error.exception javax.servlet.error.servlet_name
|