Search code examples
javaapachejspservletsweb.xml

<error-page> is not working for servlet


when exception in servlet then is not working but for jsp its work properly

web.xml code

<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error.jsp</location>
</error-page>

servlet code

protected void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException 
{
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /*
             * TODO output your page here. You may use following sample code.
             */
          String a=null;
          a.toString();//this line will throw exception
        } 
finally {            
            out.close();
        }
}

it does not redirect to error.jsp


Solution

  • Servlet code this will throw the exception to the general error page

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
               // response.setContentType("text/html;charset=UTF-8");
                PrintWriter out = response.getWriter();
                try {
                    /*
                     * TODO output your page here. You may use following sample code.
                     */
                   String a=null;
                   a.toString();
    
                }
                catch(Exception e)
                {
                    throw new ServletException(e);
                }
    
                finally {            
                    //dont write out.close();
                }
            }