[ Team LiB ] 11.3 Servlet Events Often,
[ Team LiB ] 11.3 Servlet Events Often, developers may wish to take certain special actions at various points during the life cycle of either a servlet or the application as a whole. Some of these actions can be handled by simply adding code to the appropriate life-cycle method, but other methods are not available to the general programmer. One common case is session handling. If an application could determine when a session was being expired, it would be possible to move data from the session into a database before it disappeared forever. Likewise, knowledge of when a session was being created would make it possible to move data from the database into the session. The result would be sessions that are effectively immortal, providing a seamless experience for the user. This could be achieved in many ways, but a natural mechanism is already provided by the JavaBean specification by way of events and listeners, as discussed in the preceding chapter. The idea is that the servlet engine will fire off an event representing various activities, and programmers can build listeners to capture and act on these events. Conceptually, this works just like any other bean event; it is simply a matter of implementing the right listener interfaces and working with the corresponding events. An outline of the session backup listener is shown in Listing 11.4. Listing 11.4 The outline of a session listener package com.awl.jspblog.ch11; import javax.servlet.http.*; public class BackupListenerimplements HttpSessionAttributeListener { public voidsessionCreated(HttpSessionEvent event) { HttpSession session = event.getSession(); // … load the session from the database … } public void sessionDestroyed(HttpSessionEvent event) { HttpSession session = event.getSession(); // … back up the session to the database … } public void attributeAdded(HttpSessionBindingEvent event) { // … It may not be necessary to do anything for this // event, but the interface requires it be provided } public void attributeRemoved(HttpSessionBindingEvent event) { // … It may not be necessary to do anything Page 209
Quick Hint: If you are looking for best quality webspace to host and run your tomcat application check Vision tomcat hosting services