H andling Errors And Exceptions In Servlets
  
 Introduction

The two Servlet Exceptions defined in Servlet API are:
  • javax.servlet.ServletException: Defines a servlet exception that a servlet throws while processing the client request.
  • javax.servlet.UnavailableException: Defines a servlet exception that is thrown by a servlet, when a servlet is temporarily or permanently unavailable.

Note:
  • Do not try to write to the response buffer after invoking the sendError() method
  • You can write to the response after invoking setStatus() method
Example for Handling Errors And Exceptions In Servlets

Your Ad Here

 
 Create a User Interface (Calculator.html)

<HTML>
<TITLE>ONLINE SHOPPING PORTAL</TITLE>
<BODY>
     <FORM ACTION = "http://localhost:8080/abc5/abc" METHOD = GET align=CENTER>
          Enter First Number: <INPUT TYPE = TEXT NAME = "num1" align=CENTER><BR>
          Enter Second Number: <INPUT TYPE = TEXT NAME = "num2" align=CENTER><BR>
          <INPUT TYPE = SUBMIT VALUE = "ADD" align=CENTER>
     </FORM>
</BODY>
</HTML>
Download Calculator.html

 Create a Servlet

import javax.servlet.*;
import javax.servlet.http.*;
import java.io. *;

public class Calculate extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
PrintWriter pw=res.getWriter();
int number1=Integer.parseInt(req.getParameter("num1"));
int number2=Integer.parseInt(req.getParameter("num2"));
int sum=number1+number2;
pw.println("Sum of the numbers is  "+sum);
}
}
Download Calculate.java

 Create a Customized Error Page

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class ErrorServlet extends HttpServlet
{
final String EXC = "javax.servlet.error.exception";
final String MSG = "javax.servlet.error.message";
final String ST = "javax.servlet.error.status_code";

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
ServletContext sc = getServletContext();
PrintWriter pw = response.getWriter();
Exception exc = (Exception)request.getAttribute(EXC);
Integer st_cd = (Integer)request.getAttribute(ST);
String msg = (String)request.getAttribute(MSG);
pw.println("<HTML>");
pw.println("<BODY>");
pw.println("<HR>");
pw.println("<H1>Sorry, an error has occurred that has prevented the server from servicing your request.</H1>");
pw.println("<FONT SIZE = 5>");
pw.println("<TABLE ALIGN = CENTER>");
pw.println("<TR BGCOLOR = LIGHTGREY>");
pw.println("<TD><B> Status Code : </B></TD><TD>" + st_cd + " </TD>");
pw.println("</TR>");
pw.println("<TR>");
pw.println("<TD><B> Type of Exception :</B></TD><TD>" + exc.getClass() + " </TD>");
pw.println("</TR>");
pw.println("<TR BGCOLOR = LIGHTGREY>");
pw.println("<TD><B> Message Description : </B></TD><TD>" + msg + " </TD><HR/>");
String str=exc.toString()+st_cd.toString()+msg;
sc.log("Exception occurred", exc);
pw.println("</TR>");
pw.println("</TABLE>");
pw.println("</FONT>");
pw.println("<HR>");
pw.println("<HR>");
pw.println("<CENTER><H1>Please try again...</H1></CENTER>");
pw.println("</BODY>");
pw.println("</HTML>");
}
}
Download ErrorServlet.java

 Map the Error Page to the Web Application
  1. Goto Start->Programs->Sun Microsystems->Application Server PE->Start Default Server
  2. Goto Start->Programs-> Sun Microsystems->Application Server PE->Deploytool
  3. Goto File ->New -> Application     Note:    Inserted of EmployeeDetails use Caluclate

    (Click the Browse button)


  4. (Select the folder in the Look In dropdown box, and then give a file name “Caluclate”. Next click the New Application button)


  5. (Click the OK button)
  6. Now goto File -> Save to save the file
  7. Next, goto File -> New -> Web Component

    (Click Next button)


  8. (Enter the WAR Name as “EmpApp” and then click the Edit Contents… button)


  9. (Select all the .class, .jsp , .tld and .html files and click the Add button)


  10. (Now click the OK button)


  11. (Now click the Next button)


  12. (Now select the Servlet option button and then click the Next button)


  13. (Now select the “Caluclate” from the Servlet Class dropdown box)


  14. (Now select the Next button)


  15. (Now select the Finish button)
  16. Next, goto File -> New -> Web Component

    (Click Next button)


  17. (Here, select the option Add to Existing WAR Module and select WebApp (ErrorDemo) in the WAR Location)
    (Note: WebApp is the Calculate servlets WAR Display Name and ErrorDemo is the Application Name (ie. We first created File->New->Application))


  18. (Now click the Next button)


  19. (Now select the Servlet option button and then click the Next button)


  20. (Now select the “ErrorServlet” from the Servlet Class dropdown box)


  21. (Now select the Next button)


  22. (Now select the Finish button)


  23. (Now select the EmpApp in the left pane and select the General tab in the right pane. Here give a name “example4” in the Context Root text box)
  24. Next select the Calculate in the right side

    (Now select the Calculate in the left pane and then select the Aliases tab in the right pane. Next select the Add button)


  25. (Now add a name as “Calculate”)

  26. Now select WebApp in the left pan and then select the File Refs tab in the right pane
  27. Now click the Add Error button in the Error Mapping section of the File Refs tab. Then type the exception in the Error/Exception textbox and the name of the error page in the Resource to be Called textbox. In this example use ErrorServlet-Alias-name to handle java.lang.NumberFormatException
  28. Now goto File ->Save
  29. Next goto Tools -> Deployee

    (Enter the User Name as “admin” and Password as “password”. Next click the OK button)


  30. (Now a message --- Operation Completed Successfully --- must display. Next click the Close button)
  31. Next goto File -> Exit to close it
  32. Now open an Internet Explorer and type the address http:// localhost:8080/example4/Calculate/Calculator.html

  33. Enter two values and click the add button

  34. Now enter a value in one text and a character in another text

  35. Program completed Successfully
 Click for Next Topic
PreviousNext



Your Ad Here


 About Author
Author Name           : Mr. R.Franklin Bourgia Singh
Country                    : INDIA
Working In               : Aryans Infoway (P) Ltd.
Email                        : admin@completetutorials.co.cc
Author Home Page : http://www.completetutorials.googlepages.com
 Reach me!
   My Web URL : http://www.completetutorials.googlepages.com
   If you like this article and/or code, make a small donation to my account,
Till we meet next time BYE     

  Send your feed-back and query to admin@completetutorials.co.cc
©2008 Bourgia