SET AS HOME PAGE

ADD TO FAVORITES / BOOKMARK THIS WEBSITE (More Details)

Introduction

Servlet

Jsp

Security

Enterprise Beans

Contact Us


Handling 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

CLICK HERE to download this complete example (zip file)


 Create a User Interface (Calculator.html)

<HTML>
<TITLE>ONLINE SHOPPING PORTAL</TITLE>
<BODY>
     <FORM ACTION = "http:// localhost:8080/example4/Calculate" 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. Write a html file and name it as Calculator.html
  2. Write a java program and name it as Calculate.java
  3. Write a java program and name it as ErrorServlet.java
  4. Set the path in the command prompt
    set path=.;C:\progra~1\java\j2sdk1.5.0\bin;C:\Sun\AppServer\bin;
    Set classpath=.;C:\progra~1\java\j2sdk1.5.0\lib;C:\Sun\AppServer\lib\j2ee.jar;
    (OR)
    Set the path in the system itself. CLICK HERE for details
  5. Now compile the Calculate.java and ErrorServlet.java files. CLICK HERE to see how to compile
  6. Goto Start->Programs->Sun Microsystems->Application Server PE->Start Default Server (Wait till it start and then press any key). CLICK HERE to see how to Start the Server
  7. Goto Start->Programs-> Sun Microsystems->Application Server PE->Deploytool. CLICK HERE to see how to Start the Deploytool
  8. Goto File ->New -> Application     Note:    Inserted of EmployeeDetails use Caluclate

    (Click the Browse button)


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


  10. (Click the OK button)
  11. Now goto File -> Save to save the file
  12. Next, goto File -> New -> Web Component

    (Click Next button)


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


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


  15. (Now click the OK button)


  16. (Now click the Next button)


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


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


  19. (Now select the Next button)


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

    (Click Next button)


  22. (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))


  23. (Now click the Next button)


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


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


  26. (Now select the Next button)


  27. (Now select the Finish button)


  28. (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)
  29. 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)


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

  31. Now select WebApp in the left pan and then select the File Refs tab in the right pane
  32. 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
  33. Now goto File ->Save
  34. Next goto Tools -> Deployee

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


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

  38. Enter two values and click the add button

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

  40. Program completed Successfully
  41. To stop the server goto Start -> All Programs -> Sun Microsystems -> Application Server PE -> Stop Default Server. CLICK HERE to see how to Stop the Server

 Click for Next Topic
<- PREVIOUSNEXT ->