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 ServletContextAttributeListener interface. This interface is in the javax.servlet package.

2.
Override attributeAdded, attributeReplaced, and attributeRemoved. The attributeAdded method is triggered when a new attribute is added to the servlet context. When a new value is assigned to an existing servlet context attribute, attributeAdded is triggered with the new value and attributeReplaced is triggered with the old value (i.e., the value being replaced). The attributeRemoved method 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 ServletContextAttributeListener methods takes a ServletContextAttributeEvent as an argument. The ServletContextAttributeEvent class 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 attributeReplaced 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 listener and 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.173.242