JavaWeb初识监听器

阅读: 评论:0

JavaWeb初识监听器

JavaWeb初识监听器

文章目录

  • 简要说明
  • ServletContextListener 监听器
  • 如何使用
  • 简单示例
    • 监听器配置

简要说明

1、Listener 监听器它是 JavaWeb 的三大组件Servlet 程序、Filter 过滤器、Listener监听器之一。
2、Listener 它是 JavaEE 的规范,就是接口。
3、监听器的作用是,监听某种事物的变化。然后通过回调函数,反馈给客户(程序)去做一些相应的处理。

ServletContextListener 监听器

现在常用的监听器便是ServletContextListener 监听器,它可以监听ServletContext 对象的创建和销毁。
ServletContext 对象在 web 工程启动的时候创建,在 web 工程停止的时候销毁。
监听到创建和销毁之后都会分别调用 ServletContextListener 监听器的方法反馈。

如何使用

如何使用 ServletContextListener 监听器监听 ServletContext 对象
使用步骤如下:

  • 1、编写一个类去实现 ServletContextListener
  • 2、实现其两个回调方法
  • 3、到 l 中去配置监听器

简单示例

监听器配置

public class MyServletContextListener implements ServletContextListener,HttpSessionListener, HttpSessionAttributeListener {// Public constructor is required by servlet specpublic MyServletContextListener() {}public void contextInitialized(ServletContextEvent sce) {/* This method is called when the servlet context isinitialized(when the Web application is deployed). You can initialize servlet context related data here.*/System.out.println("监听器启动");}public void contextDestroyed(ServletContextEvent sce) {/* This method is invoked when the Servlet Context (the Web application) is undeployed or Application Server shuts down.*/System.out.println("监听器销毁");}
}

这个比Servlet简单很多

<listener><listener-class>com.stackery.listener.MyServletContextListener</listener-class>
</listener>

本文发布于:2024-02-02 15:28:41,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170685892044713.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:监听器   JavaWeb
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23