How to redirect to error page in servlet?

前端 未结 3 1403
挽巷
挽巷 2021-01-20 13:39

I am writing the servlet , in case of exception I am redirecting to my customized error page for that i have done like this.

In web.xml



        
相关标签:
3条回答
  • 2021-01-20 14:10

    The problem is that you catch the Exception and therefore no Exception will leave your doPost() method. You will only be redirected error page if an Exception matching the <exception-type> (either identical or a subclass of it) leaves your doPost() method.

    You should rethrow the Exception bundled in a RuntimeException for example:

    } catch(Exception e) {
        e1.printStackTrace();
        throw new RuntimeException(e);
    }
    

    Unfortunately if we're talking about a general Exception you can't just not catch it because doPost() is declared to only throw instances of ServletException or IOException. You are allowed not to catch those, but java.lang.Exception must be caught.

    0 讨论(0)
  • 2021-01-20 14:14

    You have handled the Exception in your doPost() using ,

    try{
           //Here is all code stuff
           Throw new Exception();
    }catch(Exception e){
             e1.printStackTrace();    
    }
    

    try and catch blocks. so the errorPage.jsp will not be invoked. <error-page> is invoked for unhandled exceptions

    A nice example tutorial Exception Handling

    Read for more info Best practice error handling in JSP Servlets

    0 讨论(0)
  • 2021-01-20 14:23

    You're catching the exception, and only printing the stacktrace inside, so the error-page doesn't take affect, remove the try-catch or re-throw and it will work. In addition, you have some syntax errors. Try something like

    try{
           //Here is all code stuff
           throw new Exception();
    }catch(Exception e){
             e.printStackTrace();
             throw new ServletException();
    }
    
    0 讨论(0)
提交回复
热议问题