1 16 17 18 package listeners; 19 20 21 import javax.servlet.ServletContext ; 22 import javax.servlet.ServletContextEvent ; 23 import javax.servlet.ServletContextListener ; 24 import javax.servlet.http.HttpSessionAttributeListener ; 25 import javax.servlet.http.HttpSessionBindingEvent ; 26 import javax.servlet.http.HttpSessionEvent ; 27 import javax.servlet.http.HttpSessionListener ; 28 29 30 39 40 public final class SessionListener 41 implements ServletContextListener , 42 HttpSessionAttributeListener , HttpSessionListener { 43 44 45 47 48 51 private ServletContext context = null; 52 53 54 56 57 62 public void attributeAdded(HttpSessionBindingEvent event) { 63 64 log("attributeAdded('" + event.getSession().getId() + "', '" + 65 event.getName() + "', '" + event.getValue() + "')"); 66 67 } 68 69 70 75 public void attributeRemoved(HttpSessionBindingEvent event) { 76 77 log("attributeRemoved('" + event.getSession().getId() + "', '" + 78 event.getName() + "', '" + event.getValue() + "')"); 79 80 } 81 82 83 88 public void attributeReplaced(HttpSessionBindingEvent event) { 89 90 log("attributeReplaced('" + event.getSession().getId() + "', '" + 91 event.getName() + "', '" + event.getValue() + "')"); 92 93 } 94 95 96 101 public void contextDestroyed(ServletContextEvent event) { 102 103 log("contextDestroyed()"); 104 this.context = null; 105 106 } 107 108 109 114 public void contextInitialized(ServletContextEvent event) { 115 116 this.context = event.getServletContext(); 117 log("contextInitialized()"); 118 119 } 120 121 122 127 public void sessionCreated(HttpSessionEvent event) { 128 129 log("sessionCreated('" + event.getSession().getId() + "')"); 130 131 } 132 133 134 139 public void sessionDestroyed(HttpSessionEvent event) { 140 141 log("sessionDestroyed('" + event.getSession().getId() + "')"); 142 143 } 144 145 146 148 149 154 private void log(String message) { 155 156 if (context != null) 157 context.log("SessionListener: " + message); 158 else 159 System.out.println("SessionListener: " + message); 160 161 } 162 163 164 171 private void log(String message, Throwable throwable) { 172 173 if (context != null) 174 context.log("SessionListener: " + message, throwable); 175 else { 176 System.out.println("SessionListener: " + message); 177 throwable.printStackTrace(System.out); 178 } 179 180 } 181 182 183 } 184 | Popular Tags |