How to redirect to error page in servlet?

I am writing a servlet, in case of an exception I redirect to my modified error page because I did it like this.

In web.xml

<error-page>
  <exception-type>java.lang.Exception</exception-type>
  <location>/WEB-INF/jsp/ErrorPage.jsp</location>
</error-page>

      

In servlet

protected void doPost(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
try{
       //Here is all code stuff
       Throw new Exception();
}catch(Exception e){

         e1.printStackTrace();

}

      

But it is ErrorPage.jsp

not showing here , where am I going wrong, can someone explain to me?

+3


source to share


3 answers


The problem is that you will catch the Exception and therefore the exception will not leave your method doPost()

. The redirect page will only be redirected if a Exception

matching <exception-type>

(either identical or subclass) leaves your method doPost()

.

You have to rebuild Exception

complete with RuntimeException

for example:



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

      

Unfortunately, if we're talking general Exception

, you can't just catch it because it is doPost()

only declared for instances ServletException

or IOException

. You are allowed not to catch them, but java.lang.Exception

must be caught.

+1


source


You will catch the exception and only print the stack internally, so the error page has no effect, delete try or re-throw and it will work. Also, 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();
}

      

+2


source


You have processed Exception

in yours doPost()

using

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

      

try

and catch

. therefore errorPage.jsp

will not be called. <error-page>

thrown for unhandled exceptions

Good tutorial example Exception Handling

Read more about Error Handling in JSP Services

+1


source







All Articles