发生异常时不知道如何转发 404 页面

not getting how to forward 404 page when exception occured

我正在尝试处理 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>

您的错误在这里:您在 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>  

如果这对你有帮助,请告诉我。