views:

135

answers:

1

I was trying to run a servlet using ServletContextListener ,I've put the codes from the book "Head-First" writter "Kathy sierra", but this is not working.Its shows 404 error.I have put the class files in the directory C:\Tomcat 5.5\webapps\Listener_exe\web-inf\classes\com\example. and web.xml file in web-inf directory. So please show where I have done wrong. Here are the servlet, java files, and xml file.`

package com.example;

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

public class ListenerTester extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>test context attributes set by listener<br>");
Dog dog = (Dog) getServletContext().getAttribute("dog");
out.println("Dog's breed is: "+dog.getBreed()+</body></html>);
}
}

package com.example;

public class Dog
{
private String breed;
public Dog(String breed)
{
this.breed=breed;
}
public String getBreed()
{
return breed;
}
}

package com.example;

import javax.servlet.*;
public class MyServletContextListener implements ServletContextListener
{
public void contextInitialized(ServletContextEvent event)
{
ServletContext sc = event.getServletContext();
String dogBreed = sc.getInitParameter("breed");
Dog d = new Dog(dogBreed);
sc.setAttribute("dog",d);
}
public void contextDestroyed(ServletContextEvent event)
{}
}

<web-app>
<servlet>
<servlet-name>ListenerTester</servlet-name>
<servlet-class>com.example.ListenerTester</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ListenerTester</servlet-name>
<url-pattern>/ListenerTester</url-pattern>
</servlet-mapping>
<Context-param>
<param-name>breed</param-name>
<param-value>Great Dane</param-value>
</Context-param>
<listener>
<listener-class>
com.example.MyServletContextListener
</listener-class>
</listener>
</web-app>
A: 

Did you use the correct URL to reach the page? Your URL should be something like,

http://localhost:8080/Listener_exe/ListenerTester

Use whatever hostname or port number you set for your connector.

ZZ Coder