Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

10.3 Detecting Changes in Servlet Context Attributes

OK, when the Web application is loaded, you can set up initial values of resources and store references to them in the servlet context. But what if you want to be notified whenever these resources change? For example, what if the value of resource B depends on the value of resource A? If resource A changes, you need to automatically update the value of resource B. Handling this situation is the job of servlet context attribute listeners. Using them involves the following steps.

  1. Implement the ServletContextAttributeListenerinter-face. This interface is in the javax.servletpackage.

  2. Override attributeAdded, attributeReplaced, and attributeRemoved. The attributeAddedmethod is triggered when a new attribute is added to the servlet context. When a new value is assigned to an existing servlet context attribute, attribute-Addedis triggered with the new value and attributeReplacedis triggered with the old value (i.e., the value being replaced). The attributeRemovedmethod is triggered when a servlet context attribute is removed altogether.

  3. Obtain references to the attribute name, attribute value, and servlet context. Each of the three ServletContextAttribute-Listenermethods takes a ServletContextAttributeEventas an argument. The ServletContextAttributeEventclass has three useful methods: getName (the name of the attribute that was changed), getValue (the value of the changed attribute—the new value for attributeAdded and the previous value for attribute-Replaced and attributeRemoved), and getServletContext (the servlet context).

  4. Use the objects. You normally compare the attribute name to a stored name to see if it is the one you are monitoring. The attribute value is used in an application-specific manner. The servlet context is usually used to read previously stored attributes (getAttribute), store new or changed attributes (setAttribute), and make entries in the log file (log).

  5. Declare the listener. Use the listenerand listener-class elements to simply list the fully qualified name of the listener class, as below.

    <listener>
      <listener-class>somePackage.SomeListener</listener-class>
    </listener>

    For now, assume that this declaration goes in the web.xml file immediately before any servlet elements. However, in Section 10.5 you'll see that if you package listeners with tag libraries, you can use the identical declaration within the TLD (tag library descriptor) file of the tag library.

The following section gives an example.

  • + Share This
  • 🔖 Save To Your Account