Servlet Event Listeners: Did you know?

… you could automatically register any number of servlet event listeners (ServletContextListener, HttpSessionListener, ServletRequestListener, and more …) without any additional web.xml line?

The Java Server Pages 2.0 specification dictates that all .tld files inside META-INF directories, from jars in the web application classpath (WEB-INF/lib), must be read and parsed by the Servlet Container (JSP.7.1.9 – Event Listeners).

Fortunately, .tld files accept the <listener> element. What about creating reusable jars (web frameworks?) and do their setup inside such listeners, as Sun JSF RI (Mojarra) is doing:

<!-- jsf-impl.jar!/META-INF/jsf_core.tld -->
<taglib 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-jsptaglibrary_2_1.xsd"
  version="2.1">

  <description>
    The core JavaServer Faces custom actions that are independent of
    any particular RenderKit.
  </description>
  <tlib-version>1.2</tlib-version>
  <short-name>f</short-name>
  <uri>http://java.sun.com/jsf/core</uri>

  ...

  <!--
    This ServletContextListener initializes the runtime environment
    of the JavaServer Faces Reference Implementation when a web
    application including it is initialized by the container.
  -->
  <listener>
    <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
  </listener>

  ...
</taglib>

That said, why am I still having to add <listener> from web frameworks in my web.xml?

6 thoughts on “Servlet Event Listeners: Did you know?

  1. It’s so interesting now, where I work we have a private “web framework”, I’ll try this one.

    Thanks a lot.

  2. “That said, why am I still having to add from web frameworks in my web.xml?”

    Because if you do like you proposed, it will be dificult to change the url “extensions” 🙂

    Ok, thats probably a very bad excuse!

Leave a comment