Java Servlet Listeners.

What is Servlet Listeners?

During the lifetime of a typical web application, a number of events take place, such as:

  • requests are created or destroyed,
  • request or session attributes are added, removed, or modified,
and so on and so forth.

The Servlet API provides a number of listener interfaces we can implement in order to react to these events.

Listener Interface Description
ServletContextListener Contains methods for handling context initialization and destruction events.
ServletContextAttributeListener Contains methods for reacting to any attributes added, removed, or replaced in the servlet context (application scope).
ServletRequestListener Contains methods for handling request initialization and destruction events.
ServletRequestAttributeListener Contains methods for reacting to any attributes added, removed, or replaced in the request.
HttpSessionListener Contains methods for handling HTTP session initialization and destruction events.
HttpSessionAttributeListener Contains methods for reacting to any attributes added, removed, or replaced in the HTTP session.

All we need to do is to implement one or more of these interfaces and then:

  • annotate the implemented class(es) with the @WebListener() annotation or
  • declare the implemented class(es) in the web.xml (deployment descriptor) via the <listener> tag.

@WebListener() annotation has only one option parameter, value="", which is for description of the listener.

Using Annotation example:
@WebListener()
public class RequestListener implements ServletRequestListener {
  public void requestDestroyed(ServletRequestEvent sre) {...}
  public void requestInitialized(ServletRequestEvent sre) {...}
}
Using deployment descriptor (web.xml) example:
<web-app .....>
 <listener>
    <listener-class>RequestListener</listener-class>         <!-- required  -->   
    <display-name></display-name>             <!-- optional  -->
    <description></description>               <!-- optional  -->
    <icon></icon>                             <!-- optional  -->
  </listener>
</web-app>

Example of Servlet listeners.

As selected we use Netbeans IDE and Glassfish Server.

You can download this example here (needed tools can be found in the right menu on this page).

If you like to participate in the review of this example you must first create a Web project in Netbeans (the project name is ServletListener).

  • We start with the Listener class:
    package app.simple;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletRequestEvent;
    import javax.servlet.ServletRequestListener;
    import javax.servlet.annotation.WebListener;
    
    @WebListener()
    public class RequestListener implements ServletRequestListener {
      @Override
      public void requestDestroyed(ServletRequestEvent sre) {
        ServletContext servletContext = sre.getServletContext();
        servletContext.log("Request destroyed");
        System.out.println("System.out: Request destroyed");
      }
      @Override
      public void requestInitialized(ServletRequestEvent sre) {
        ServletContext servletContext = sre.getServletContext();
        servletContext.log("New request initialized");
        System.out.println("System.out: New request initialized");
      }
    }

    For those who participate in the review: create a Class in Netbeans and replace generated code for the class with that shown above (the class name is RequestListener).

  • We need a simple servlet:
    package app.simple;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletContext;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    @WebServlet("/")
    public class SimpleServlet extends HttpServlet
    {
      @Override
      protected void doGet(HttpServletRequest request,HttpServletResponse response) {
        try    {
          ServletContext servletContext=request.getServletContext();
          servletContext.log("Starting SimpleServlet");
          System.out.println("System.out: Starting SimpleServlet");
          response.setContentType("text/html");
          PrintWriter printWriter = response.getWriter();
          printWriter.println("<h3>");
          printWriter.println("Testing the Request events");
          printWriter.println("</h3>");
          servletContext.log("Ending SimpleServlet");
          System.out.println("System.out: Ending SimpleServlet");
        } catch (IOException ioException)    {
          request.getServletContext().log(ioException.getMessage());
        }
      }
    }

    For those who participate in the review: create a Servlet in Netbeans and replace generated code for the servlet with that shown above (the servlet name is SimpleServlet).

Creating Deployment descriptor.

  • To run this Servlet you have to deploy it to a web-server or a Application server. To deploy means to install the Servlet with some instruction to a such server.
  • When using annotation instructions are mainly defined in the code. The rest of the instructions should be in the deployment descriptor, web.xml.

    For those who participate in the review: create a Standard web descriptor in Netbeans and create a welcome-file tag as shown below.

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
    http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             version="3.1">
      <session-config>
        <session-timeout>
          30
        </session-timeout>
      </session-config>
      <welcome-file-list>
        <welcome-file></welcome-file>
      </welcome-file-list>
    </web-app>
  • This file starts with the normal xml tag for a XML file and the root tag for the deployment descriptor is web-app.
  • If no session-timeout (the server ends the service of the application after this time) is given a standard timeout for the server is used as timeout for the application.
  • The welcome-file tag specifies the startup for our application, which in this case and our application is the servlet with url /.

Creating Web-server Deployment descriptor.

  • The context-root (in example /ServletListener) for the application will in most cases be specified by a server vendor deployment descriptor.

    For those who participate in the review: create a deployment descriptor in Netbeans.

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, 
    Inc.//DTD GlassFish Application Server 3.0 Servlet 3.0//EN" 
    "http://www.sun.com/software/appserver/dtds/sun-web-app_3_0-0.dtd">
    <sun-web-app error-url="">
      <context-root>/ServletListener</context-root>
      <class-loader delegate="true"/>
      <jsp-config>
        <property name="keepgenerated" value="true">
          <description>
            Keep a copy of the generated servlet class' java code.
          </description>
        </property>
      </jsp-config>
    </sun-web-app>

Run the application.

  • For those who participate in the review: right click the Web-project and select Run.
  • This results in that the application will be deployed to the server and started.
  • The browser will display:

    Testing the Request events

    To show what is going on you must look at the server log file.
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.