Solved

servlet exception handling

Posted on 2014-02-23
11
1,292 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
  • 5
  • 3
  • 3
11 Comments
 
LVL 19

Assisted Solution

by:Ken Butters
Ken Butters earned 200 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
 
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 20

Accepted Solution

by:
chaitu chaitu earned 300 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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
The viewer will learn how to implement Singleton Design Pattern in Java.

747 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now