Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

servlet exception handling

Hi,

I am working on below example

http://www.tutorialspoint.com/servlets/servlets-exception-handling.htm


my code looks like below

package com.tp.first;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.GregorianCalendar;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloWorld
 */
@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
      private static final long serialVersionUID = 1L;
      private String message;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloWorld() {
        super();
        // TODO Auto-generated constructor stub
    }

      /**
       * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
       */
   
    public void init() throws ServletException
    {
        // Do required initialization
        message = "Hello World";
    }

    // Method to handle GET method request.
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
              throws ServletException, IOException
    {
        // Analyze the servlet exception      
        Throwable throwable = (Throwable)
        request.getAttribute("javax.servlet.error.exception");
        Integer statusCode = (Integer)
        request.getAttribute("javax.servlet.error.status_code");
        String servletName = (String)
        request.getAttribute("javax.servlet.error.servlet_name");
        if (servletName == null){
           servletName = "Unknown";
        }
        String requestUri = (String)
        request.getAttribute("javax.servlet.error.request_uri");
        if (requestUri == null){
           requestUri = "Unknown";
        }

        // Set response content type
        response.setContentType("text/html");
   
        PrintWriter out = response.getWriter();
          String title = "Error/Exception Information";
        String docType =
        "<!doctype html public \"-//w3c//dtd html 4.0 " +
        "transitional//en\">\n";
        out.println(docType +
          "<html>\n" +
          "<head><title>" + title + "</title></head>\n" +
          "<body bgcolor=\"#f0f0f0\">\n");

        if (throwable == null && statusCode == null){
           out.println("<h2>Error information is missing</h2>");
           out.println("Please return to the <a href=\"" +
             response.encodeURL("http://localhost:8080/") +
             "\">Home Page</a>.");
        }else if (statusCode != null){
           out.println("The status code : " + statusCode);
        }else{
           out.println("<h2>Error information</h2>");
           out.println("Servlet Name : " + servletName +
                               "</br></br>");
           out.println("Exception Type : " +
                               throwable.getClass( ).getName( ) +
                               "</br></br>");
           out.println("The request URI: " + requestUri +
                               "<br><br>");
           out.println("The exception message: " +
                                   throwable.getMessage( ));
        }
        out.println("</body>");
        out.println("</html>");
    }
      /**
       * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
       */
    // Method to handle POST method request.
    public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
        throws ServletException, IOException {
       doGet(request, response);
    }

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>TutorialPointServletProj</display-name>
 
<!--   <filter>
   <filter-name>LogFilter</filter-name>
   <filter-class>LogFilter</filter-class>
   <init-param>
	  <param-name>test-param</param-name>
	  <param-value>Initialization Paramter</param-value>
   </init-param>
</filter>
<filter-mapping>
   <filter-name>LogFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping> -->

<error-page>
    <error-code>404</error-code>
    <location>/ErrorHandler</location>
</error-page>
<error-page>
    <exception-type>java.lang.Throwable</exception-type >
    <location>/ErrorHandler</location>
</error-page>
</web-app>

Open in new window


when i ran the servlet i did not get output that is mentioned in the link as below

The status code : 404


Instead i got output like below

Error information is missing
Please return to the Home Page.

when i click Home Page link
I see some raw error message like
HTTP Status 404 - /

--------------------------------------------------------------------------------

type Status report

message /

description The requested resource is not available.


--------------------------------------------------------------------------------

Apache Tomcat/7.0.52

instead of

The status code : 404
SOLUTION
Avatar of Ken Butters
Ken Butters
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Reviewing your code.

I don't see that you included code for ErrorHandler.java
Did you include that source code and then compile it?
It should look something like this:

package com.tp.first;

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import javax.servlet.annotation.WebServlet;


// Extend HttpServlet class
@WebServlet("/ErrorHandler")
public class ErrorHandler extends HttpServlet {
 
  // Method to handle GET method request.
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // Analyze the servlet exception       
      Throwable throwable = (Throwable)
      request.getAttribute("javax.servlet.error.exception");
      Integer statusCode = (Integer)
      request.getAttribute("javax.servlet.error.status_code");
      String servletName = (String)
      request.getAttribute("javax.servlet.error.servlet_name");
      if (servletName == null){
         servletName = "Unknown";
      }
      String requestUri = (String)
      request.getAttribute("javax.servlet.error.request_uri");
      if (requestUri == null){
         requestUri = "Unknown";
      }

      // Set response content type
      response.setContentType("text/html");
 
      PrintWriter out = response.getWriter();
	  String title = "Error/Exception Information";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
        "<html>\n" +
        "<head><title>" + title + "</title></head>\n" +
        "<body bgcolor=\"#f0f0f0\">\n");

      if (throwable == null && statusCode == null){
         out.println("<h2>Error information is missing</h2>");
         out.println("Please return to the <a href=\"" + 
           response.encodeURL("http://localhost:8080/") + 
           "\">Home Page</a>.");
      }else if (statusCode != null){
         out.println("The status code : " + statusCode);
      }else{
         out.println("<h2>Error information</h2>");
         out.println("Servlet Name : " + servletName + 
                             "</br></br>");
         out.println("Exception Type : " + 
                             throwable.getClass( ).getName( ) + 
                             "</br></br>");
         out.println("The request URI: " + requestUri + 
                             "<br><br>");
         out.println("The exception message: " + 
                                 throwable.getMessage( ));
      }
      out.println("</body>");
      out.println("</html>");
  }
  // Method to handle POST method request.
  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
     doGet(request, response);
  }
}

Open in new window

Avatar of gudii9

ASKER

Have you set up the hello world example:
http://www.tutorialspoint.com/servlets/servlets-first-example.htm

When you run this example do you see "Hello World"?


Somehow that is not running. I am not able to find and make those setting changes. I am taking one other HelloWorld example which is working modifying the doGet method in that for every other new example.
The reason I asked about the Hello World... that gives some indication if the rest of your project is set up correctly.

The big problem I see with your original question is that I don't see that you included the ErrorHandler class.

But... I think you need a solid foundation of a working example before moving on to error handling.
Avatar of gudii9

ASKER

When I try to create Servlet by adding web.xml mapping entry giving error saying HelloWorld servlet name already exists. How to fix this.


I just created separate dynamic webprojec callled WebExample and put this servlet. There is no other servlet woth same name but i still get error saying 'same servlet already existing' like that. Doe eclipse check all other dynamic web projects and see if any other servlet with same name?
I see on HelloWorld.jsp is there in one other project but not servlet.


If I use annotation as below

package com.gp;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloWorld
 */
@WebServlet("/HelloWorld2")
public class HelloWorld2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String message;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloWorld2() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */

    public void init() throws ServletException
    {
        // Do required initialization
        message = "Hello World";
    }

    public void doGet(HttpServletRequest request,
            HttpServletResponse response)
    throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");

// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

Open in new window




Do I still need to have web.xml?
Can I remove web.xml as annotation is taking care of the configuration.

I wrote code as above and ran on tomcat 7 server. When i right click on the servlet and said Run As --->Server
I do not see browser page opened automatically as below on my other laptop.
http://localhost:8080/HelloWorld2
Do I need to do make any set up changes so that IE automcatically opens and go to URL
http://localhost:8080/HelloWorld2


I am not able to run this annotation example on tomcat6 says only supports 1.3, 1.4, 1.5 only.

please advise if i only have to use tomcat7 and beyond?
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
when you use tomcat 6 then you should select dynamic project version as 2.5.

to change the version do the following step.

right clik on the project--properties--Project facets--Dynamic Web Module--select version as 2.5

for tomcat  7 you can select  Dynamic Web Module version as 3.0
Avatar of gudii9

ASKER

oh I will try and let you know.
Avatar of gudii9

ASKER

It worked on the tomcat7. When i tried tomcat 6 and tried as below

right clik on the project--properties--Project facets--Dynamic Web Module--select version as 2.5


I am getting error as attached. How to fix it. please advise
ProjectFacets.jpg
check this link

http://stackoverflow.com/questions/18122336/cannot-change-version-of-project-facet-dynamic-web-module-to-3-0

may be you need to change the wep app version as 2.5 in web.xml
Avatar of gudii9

ASKER

may be you need to change the wep app version as 2.5 in web.xml

how and where to change. my web.xml is like

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>Simple</servlet-name>
    <servlet-class>Simple</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>WelcomeServlet</servlet-name>
    <servlet-class>WelcomeServlet</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>Simple</servlet-name>
    <url-pattern>/go</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>WelcomeServlet</servlet-name>
    <url-pattern>/welcome</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>login.html</welcome-file>
  </welcome-file-list>
</web-app>

Open in new window