JavaWeb 三大组件之监听器 Listener
Listener
- Listener 监听器它是 JavaWeb 的三大组件之一。JavaWeb 的三大组件分别是:Servlet 程序、Listener 监听器、Filter 过滤器
- Listener 是 JavaEE 的规范,就是接口
- 监听器的作用是,监听某种变化(一般就是对象创建/销毁, 属性变化), 触发对应方法完成相应的任务
- JavaWeb 中的监听器(共八个), 目前最常用的是 ServletContextListener,
JavaWeb 的监听器
ServletContextListener 监听器
- 作用:监听 ServletContext 创建或销毁(当我们 Web 应用启动时,就会创建 ServletContext),即生命周期监听,应用场景(1)加载初始化的配置文件;比如 spring 的配置文件 (2)任务调度(配合定时器 Timer/TimerTask)
- 相关方法
@WebListener()
public class LGQServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext servletContext = servletContextEvent.getServletContext();
System.out.println("监听器监听到servletContext被创建" + servletContext);
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
ServletContext servletContext = servletContextEvent.getServletContext();
System.out.println("监听器监听到servletContext被销毁" + servletContextEvent);
}
}
ServletContextAttributeListener 监听器
- 作用:监听 ServletContext 属性变化
- 相关方法
@WebListener
public class LGQServletContextAttributeListener implements ServletContextAttributeListener {
@Override
public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) {
System.out.println("监听到属性被创建:" + servletContextAttributeEvent.getName() + " "
+ servletContextAttributeEvent.getValue());
}
@Override
public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) {
System.out.println("监听到属性被删除:" + servletContextAttributeEvent.getName() + " "
+ servletContextAttributeEvent.getValue());
}
@Override
public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) {
System.out.println("监听到属性被替换:" + servletContextAttributeEvent.getName() + " "
+ servletContextAttributeEvent.getValue());
}
}
@WebServlet(urlPatterns = "/ServletContextAttributeServlet")
public class ServletContextAttributeServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = req.getServletContext();
servletContext.setAttribute("123", "aegf");
servletContext.setAttribute("124", "t43wt");
servletContext.setAttribute("123", "123");
servletContext.removeAttribute("124");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);