jump to navigation

ServletContext Listener August 24, 2005

Posted by Coolguy in Java.
Tags:
trackback
  • To listen for ServletContext events write a listener class that implements
    javax.servlet.ServletContextListener;
    and tell the container by putting a <listener> element in DD.
  • This class will get notifed when context is initialized and destroyed
  • E.g:
    web.xml
    <context-param>
    <param-name>breed</param-name>
    <param-value>poodle</param-value>
    </context-param>
    <listener>
    <listener-class>
    test.MyServletContextListener
    </listener-class>
    </listener>
    <servlet>
    <description></description>
    <display-name>ListenerTest</display-name>
    <servlet-name>ListenerTest</servlet-name>
    <servlet-class>test.ListenerTest</servlet-class>
    </servlet>
    Listener Class
    import javax.servlet.*;
    public class MyServletContextListener implements ServletContextListener{
    public void contextInitialized(ServletContextEvent se)
    {
    ServletContext sc=se.getServletContext();
    String breed=sc.getInitParameter(“breed”);
    Dog d = new Dog(breed);
    sc.setAttribute(“dog”,d);
    }
    public void contextDestroyed(ServletContextEvent se)
    {
    }
    }
    Testing servlet
    import java.io.IOException;
    import java.io.PrintWriter;import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class ListenerTest extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
    public ListenerTest()
    {
    super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
    response.setContentType(“text/html”);
    PrintWriter out = response.getWriter();
    Dog dog = (Dog) getServletContext().getAttribute(“dog”);
    out.println(dog.getBreed());
    }

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

Advertisements

Comments»

No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: