我试图在servlet中处理ArithmeticException,catch块是
正在执行但没有转发到错误页面。
我得到了ArithmeticException: / by zero
有人可以说明为什么它没有转发给general-errorpage.jsp
web.xml
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/ErrorHandler</location>
</error-page>
<error-page>
<location>/general-errorpage.jsp</location>
</error-page>
Servlet:
@WebServlet("/ErrorHandler")
public class Abc extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
int a=1,b=0,c=0;
Throwable throwable = (Throwable)
request.getAttribute("javax.servlet.error.exception");
String servletName = (String)
request.getAttribute("javax.servlet.error.servlet_name");
try{
c= a/b;
}
catch(ArithmeticException e) {
e.printStackTrace();
request.setAttribute("error", "Servlet " + servletName +
" has thrown an exception " + throwable.getClass().getName()
+
" : " + throwable.getMessage() );
request.getRequestDispatcher("/general-
errorpage.jsp").forward(request, response);
}
}
错误页面为:
<%@ page isErrorPage="true" import="java.io.*" contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Error Page - </title>
</head>
<body>
<table><tr><td>${statusCode}</td></tr></table>
</body>
</html>
答案 0 :(得分:1)
您的错误就在这里:您在web.xml中编写的代码甚至无法编译,因为无论何时使用<error-page>
,您都必须拥有<exception-type>
或<exception-code>
标记。
<error-page>
<location>/general-errorpage.jsp</location>
</error-page>
因此请在您的web.xml中进行更改。通过使用它,您可以处理任何类型的异常:(您还可以将异常类型保留为java.lang.Throwable)
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/general-errorpage.jsp</location>
</error-page>
我想补充一点,如果你想处理特定错误代码的异常,那么你可以这样做:
<error-page>
<error-code>500</error-code>
<location>/general-errorpage.jsp</location>
</error-page>
如果这有助于您,请告诉我。