• SQL Tutorial
  • Struts
  • jQuery
  • PHP
  • Core Java
  • RubyonRails
  • JSP
  • JavaScript
  • Spring

  • <

    Servlet Exception Handling Tutorial

    Exception occurs when program is executed.It convert system error messages into user friendly error messages. This is one of the powerful feature of Java to handle run time error and maintain normal flow of java application.


    Exception Types of Errors


  • java.lang.RuntimeException, Error
  • jjavax.servlet.ServletException
  • jjava.io.IOException

  • Servlet Exception Handling Example


    index.html
    <form action="servlet1">
    Name:<input type="text" name="userName"/> <input type="submit" value="continue"/> </form>


    Servlet.java
    
    import java.io.*;   
    import javax.servlet.*;   
    import javax.servlet.http.*;   
     
    public class Servlet extends HttpServlet {   
       
      public void doPost(HttpServletRequest request, HttpServletResponse response){   
        try
    {   
       
        response.setContentType("text/html");   
        PrintWriter out = response.getWriter();   
               
        String n=request.getParameter("userName");  
        out.print("Welcome "+n);   
       
        Cookie ck=new Cookie("uname",n);//creating cookie object  
        response.addCookie(ck);//adding cookie in the response   
       
        //creating submit button   
        out.print("<form action='servlettwo'>");   
        out.print("<input type='submit' value='continue'>");   
        out.print("</form>");  
         out.close();   
      
            }catch(Exception e){System.out.println(e);
    }   
      }  
    } 
    
    


    error.html
    
    <html>   
    <body>   
    <p> Oooops....... page not found</p>  
    </body>  
    </html>  
    


    Servlettwo.java
    
    import java.io.*; 
    import javax.servlet.*; 
     
    public class Servlet extends HttpServlet {   
      
      public void service(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException 
      { 
       // get request parameter 
       // business operation 
       String resultvalue="<body bgcolor="cyan" text="red"> <h1> hello word</h1></body>"; 
     
       // prepare response 
       resp.setContentType("text/html"); 
       printWriter out=resp.getWriter();
    
       // send response 
       out.print(resultvalue);   
       out.close();   
       }   
    }  
    


    web.xml
    
    <web-app>   
    <servlet>   
    <servlet-name>s1</servlet-name>  
    <servlet-class>Servlet</servlet-class>   
    </servlet>   
    
    <error-page> 
    <exception-type>java.lang.NumberFormateException</exception-type>   
    <location>/error.html</location>   
    
    </error-page>   
    
    </web-app>  
    
















    © copyright 2017-2021 Completedone pvt ltd.