JavaWeb之监听器
1. 介绍
监听器是一个专门用于对其他对象身上发生的事件或状态改变进行监听和相应处理的对象,当被监视的对象发生情况时,立即采取相应的行动。监听器其实就是一个实现特定接口的普通java程序,这个程序专门用于监听另一个java对象的方法调用或属性改变,当被监听对象发生上述事件后,监听器某个方法立即被执行。
2. 监听器分类
(1)ServletContextListener监听器,监听ServletContext的初始化和销毁。
- contextInitialized:初始化contextInitialized的时候出发。
- contextDestroyed:销毁ServletContextde的时候触发。
(2)ServletContextAttributeListener监听器,监听ServletContext属性的操作。
- attributeAdded:新增ServletContext属性的时候触发。
- attributeRemoved:删除ServletContext属性的时候触发。
- attributeReplaced:改写ServletContext属性的时候触发。
(3)HttpSessionListener监听器,监听HttpSession的初始化和销毁。
- sessionCreated:初始化HttpSession的时候触发。
- sessionDestroyed:销毁HttpSession的时候触发。
(4)HttpSessionAttributeListener监听器,监听HttpSession属性的操作。
- attributeAdded:新增HttpSession属性的时候触发。
- attributeRemoved:删除HttpSession属性的时候触发。
- attributeReplaced:改写HttpSession属性的时候触发。
(5)ServletRequestListener监听器,监听ServletRequest的初始化和销毁。
- requestInitialized:初始化ServletRequest的时候触发。
- requestDestroyed:销毁ServletRequest的时候触发。
(6)ServletRequestAttributeListener监听器,监听ServletRequest属性的操作。
- attributeAdded:新增ServletRequest属性的时候触发。
- attributeRemoved:删除ServletRequest属性的时候触发。
- attributeReplaced:改写ServletRequest属性的时候触发。
3. 测试监听器触发时机
首先,我们要新建一个Web Project。然后分别建立这六种监听器,并加上输出到控制台的代码:
ServletContextListener
package com.servlet.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class MyContextListener implements ServletContextListener{ @Override public void contextDestroyed(ServletContextEvent arg0) { System.out.println("--------------ContextListener Destoryed"); } @Override public void contextInitialized(ServletContextEvent arg0) { System.out.println("--------------ContextListener Initialized"); } }
ServletContextAttributeListener
package com.servlet.listener; import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; public class MyServletContextAttributeListener implements ServletContextAttributeListener { @Override public void attributeAdded(ServletContextAttributeEvent arg0) { System.out.println("--------------ServletContextAttributeEvent Add "+arg0.getValue().toString()); } @Override public void attributeRemoved(ServletContextAttributeEvent arg0) { System.out.println("--------------ServletContextAttributeEvent Remove "+arg0.getValue().toString()); } @Override public void attributeReplaced(ServletContextAttributeEvent arg0) { System.out.println("--------------ServletContextAttributeEvent Replace "+arg0.getValue().toString()); } }
HttpSessionListener
package com.servlet.listener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class MyHttpSessionListener implements HttpSessionListener{ @Override public void sessionCreated(HttpSessionEvent arg0) { System.out.println("--------------HttpSessionListener Created"); } @Override public void sessionDestroyed(HttpSessionEvent arg0) { System.out.println("--------------HttpSessionListener Destoryed"); } }
HttpSessionAttributeListener
package com.servlet.listener; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; public class MyHttpSessionAttributeListener implements HttpSessionAttributeListener { @Override public void attributeAdded(HttpSessionBindingEvent arg0) { System.out.println("--------------HttpSessionAttributeListener Add "+arg0.getValue().toString()); } @Override public void attributeRemoved(HttpSessionBindingEvent arg0) { System.out.println("--------------HttpSessionAttributeListener Remove "+arg0.getValue().toString()); } @Override public void attributeReplaced(HttpSessionBindingEvent arg0) { System.out.println("--------------HttpSessionAttributeListener Replace "+arg0.getValue().toString()); } }
ServletRequestListener
package com.servlet.listener; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; public class MyServletRequestLister implements ServletRequestListener{ @Override public void requestDestroyed(ServletRequestEvent arg0) { System.out.println("--------------ServletRequestLister Destoryed"); } @Override public void requestInitialized(ServletRequestEvent arg0) { System.out.println("--------------ServletRequestLister Initialized"); } }
ServletRequestAttributeListener
package com.servlet.listener; import javax.servlet.ServletRequestAttributeEvent; import javax.servlet.ServletRequestAttributeListener; public class MyServletRequestAttributeListener implements ServletRequestAttributeListener { @Override public void attributeAdded(ServletRequestAttributeEvent arg0) { System.out.println("--------------ServletRequestAttributeEvent Add "+arg0.getValue().toString()); } @Override public void attributeRemoved(ServletRequestAttributeEvent arg0) { System.out.println("--------------ServletRequestAttributeEvent Remove "+arg0.getValue().toString()); } @Override public void attributeReplaced(ServletRequestAttributeEvent arg0) { System.out.println("--------------ServletRequestAttributeEvent Replace "+arg0.getValue().toString()); } }
然后我们为程序加上要访问的Servlet:
package com.servlet.action; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HelloServlet extends HttpServlet { private static final long serialVersionUID = -5826456046908414493L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("--------------HelloServlet get param "+req.getParameter("userName")); System.out.println("--------------Before HelloServlet add session attribute "); req.getSession().setAttribute("userName", "userName1"); System.out.println("--------------After HelloServlet add session attribute "); System.out.println("--------------Before HelloServlet replace session attribute "); req.getSession().setAttribute("userName", "userName2"); System.out.println("--------------After HelloServlet replace session attribute "); System.out.println("--------------Before HelloServlet remove session attribute "); req.getSession().removeAttribute("userName"); System.out.println("--------------After HelloServlet remove session attribute "); } @Override public void destroy() { System.out.println("--------------HelloServlet Destory"); } @Override public void init() throws ServletException { System.out.println("--------------HelloServlet Init"); super.init(); } }
然后我们在web.xml中做如下配置:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" 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-app_3_0.xsd"> <listener> <listener-class>com.servlet.listener.MyContextListener</listener-class> </listener> <listener> <listener-class>com.servlet.listener.MyHttpSessionListener</listener-class> </listener> <listener> <listener-class>com.servlet.listener.MyServletRequestLister</listener-class> </listener> <listener> <listener-class>com.servlet.listener.MyServletContextAttributeListener</listener-class> </listener> <listener> <listener-class>com.servlet.listener.MyHttpSessionAttributeListener</listener-class> </listener> <listener> <listener-class>com.servlet.listener.MyServletRequestAttributeListener</listener-class> </listener> <servlet> <!-- 名称可以随意更换,但是必须和<servlet-mapping>中<servlet-name>保持一致 --> <servlet-name>Hello</servlet-name> <!-- 对应的实现了servlet接口的类的全名 --> <servlet-class>com.servlet.action.HelloServlet</servlet-class> </servlet> <servlet-mapping> <!-- 名称可以随意更换,但是必须和<servlet>中<servlet-name>保持一致 --> <servlet-name>Hello</servlet-name> <!-- 要访问的URL --> <url-pattern>/Hello</url-pattern> </servlet-mapping> <session-config> <session-timeout>1</session-timeout> </session-config> </web-app>
最后将我们的程序部署到tomcat中,启动tomcat,访问:http://127.0.0.1:8080/MyServletWeb/Hello?userName=LYC。可以看到打印结果为:
三月 17, 2016 9:03:46 下午 org.apache.catalina.core.StandardService startInternal INFO: Starting service Catalina 三月 17, 2016 9:03:46 下午 org.apache.catalina.core.StandardEngine startInternal INFO: Starting Servlet Engine: Apache Tomcat/7.0.62 三月 17, 2016 9:03:46 下午 org.apache.catalina.startup.HostConfig deployDirectory INFO: Deploying web application directory D:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\MyServletWeb --------------ContextListener Initialized --------------ServletContextAttributeEvent Add org.apache.jasper.compiler.TldLocationsCache@170ed6ab 三月 17, 2016 9:03:46 下午 org.apache.catalina.startup.HostConfig deployDirectory INFO: Deployment of web application directory D:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\MyServletWeb has finished in 828 ms 三月 17, 2016 9:03:46 下午 org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["http-bio-8080"] 三月 17, 2016 9:03:47 下午 org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["ajp-bio-8009"] 三月 17, 2016 9:03:47 下午 org.apache.catalina.startup.Catalina start INFO: Server startup in 888 ms --------------ServletRequestLister Initialized --------------HelloServlet Init --------------ServletRequestAttributeEvent Replace true --------------HelloServlet get param LYC --------------Before HelloServlet add session attribute --------------HttpSessionAttributeListener Add userName1 --------------After HelloServlet add session attribute --------------Before HelloServlet replace session attribute --------------HttpSessionAttributeListener Replace userName1 --------------After HelloServlet replace session attribute --------------Before HelloServlet remove session attribute --------------HttpSessionAttributeListener Remove userName2 --------------After HelloServlet remove session attribute --------------ServletRequestLister Destoryed 三月 17, 2016 9:03:59 下午 org.apache.catalina.core.StandardServer await INFO: A valid shutdown command was received via the shutdown port. Stopping the Server instance. 三月 17, 2016 9:03:59 下午 org.apache.coyote.AbstractProtocol pause INFO: Pausing ProtocolHandler ["http-bio-8080"] 三月 17, 2016 9:04:00 下午 org.apache.coyote.AbstractProtocol pause INFO: Pausing ProtocolHandler ["ajp-bio-8009"] 三月 17, 2016 9:04:00 下午 org.apache.catalina.core.StandardService stopInternal INFO: Stopping service Catalina --------------HelloServlet Destory --------------ContextListener Destoryed 三月 17, 2016 9:04:00 下午 org.apache.coyote.AbstractProtocol stop INFO: Stopping ProtocolHandler ["http-bio-8080"] 三月 17, 2016 9:04:00 下午 org.apache.coyote.AbstractProtocol stop INFO: Stopping ProtocolHandler ["ajp-bio-8009"] 三月 17, 2016 9:04:00 下午 org.apache.coyote.AbstractProtocol destroy INFO: Destroying ProtocolHandler ["http-bio-8080"] 三月 17, 2016 9:04:00 下午 org.apache.coyote.AbstractProtocol destroy INFO: Destroying ProtocolHandler ["ajp-bio-8009"]