Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

servlet exception handling

Posted on 2014-02-23
11
Medium Priority
?
1,445 Views
Last Modified: 2014-04-02
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
0
Comment
Question by:gudii9
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 3
11 Comments
 
LVL 19

Assisted Solution

by:Ken Butters
Ken Butters earned 800 total points
ID: 39886258
Before you start on the exception handling of servlets... it might be a good idea to make sure that your environment is set up correctly.

You can confirm that with a simpler example in the same tutorioal you linked to in your original post.

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"?

Also... are you working in eclipse, like your other posts, or are you following the tutorial, and building the directory structures for Tomcat yourself?
0
 
LVL 19

Expert Comment

by:Ken Butters
ID: 39886996
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

0
 
LVL 7

Author Comment

by:gudii9
ID: 39889341
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.
0
Setting up LaraDock for Laravel

Learn how to set up LaraDock in a Laravel project - LaraDock gives us an easy way to run a Laravel application using Docker in a single command.

 
LVL 19

Expert Comment

by:Ken Butters
ID: 39889443
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.
0
 
LVL 7

Author Comment

by:gudii9
ID: 39954409
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?
0
 
LVL 20

Accepted Solution

by:
chaitu chaitu earned 1200 total points
ID: 39955155
I ran this example in tomcat 7 its working fine.web.xml is not required.

i think you missed the contextname in the url.

http://localhost:8080/servletexample/HelloWorld2
0
 
LVL 20

Expert Comment

by:chaitu chaitu
ID: 39955185
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
0
 
LVL 7

Author Comment

by:gudii9
ID: 39957369
oh I will try and let you know.
0
 
LVL 7

Author Comment

by:gudii9
ID: 39957426
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
0
 
LVL 20

Expert Comment

by:chaitu chaitu
ID: 39957892
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
0
 
LVL 7

Author Comment

by:gudii9
ID: 39959949
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

0

Featured Post

Docker-Compose to Simplify Multi-Container Builds

Our veteran DevOps Author takes you through how to build a multi-container environment, managed with a single utility in order to simplify your deployments.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
This video teaches viewers about errors in exception handling.
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

721 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question