hi everyone,
could some one please help me with showing me what i have done wrong in this web app. i have tried so many times to get this to work but failed and i have turned to you guys out there who can help me. following are the codes for my web app. it consists of one
servlet, one servletcontext listener class, one helper class and the web.xml class. its actually code given in the hfsj book. there is no html involved. the code is as follows.
the MyServletContextListener class is as follows;
package com.example;
import com.example.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServletContextListener implements ServletContextListener{
public void contextInitialized(ServletContextEvent event){
ServletContext sc = event.getServletContext();
String doBreed = sc.getInitParameter("breed");
Dog d = new Dog(doBreed);
sc.setAttribute("dog",doBreed);
}
public void contextDestroyed(ServletContextEvent event){
}
}
the servlet class is as follows;
package com.example;
import com.example.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import javax.servlet.*;
public class ListenerTester extends HttpServlet{
public void goGet(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("test context attributes set by listener<br>");
out.println("<br>");
String dog = (String) (getServletContext().getAttribute("dog"));
out.println("Dog's breed is " + dog);
}
}
the helper class is as follows;
package com.example;
public class Dog{
private String breed;
public Dog(String breed){
this.breed = breed;
}
public String getBreed(){
return breed;
}
}
and finally the web.xml file is as follows;
<?xml version="1.0" encoding= "ISO-8859-1" ?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
verion="2.4">
<servlet>
<servlet-name>ListenerTester</servlet-name>
<servlet-class>com.example.ListenerTester</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ListenerTester</servlet-name>
<url-pattern>/ListenTest.do</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>
when i put them in the appropriate folders in the development enviroment i get an error report. but what should happen is i should get the paramaeter value which is great dane and set it as a servletcontext attribute and call it from the servlet class and hence to prove that it was initialized before any servlet class was initialized. please help.
thank you
Dinuka Arseculeratne