[Java]监听器(Listener)

过滤器(Filter)icon-default.png?t=N3I4https://blog.csdn.net/m0_71229255/article/details/130246404?spm=1001.2014.3001.5501

一 : Listener监听器简述

监听器就是监听某个对象的的状态变化的组件

监听器的相关概念:

  • 事件源:
    被监听的对象 ----- 三个域对象 request session servletContext

  • 监听器 :
    监听事件源对象的状态的变化都会触发监听器

  • 注册监听器 :
    将监听器与事件源进行绑定

  • 响应行为 :
    监听器监听到事件源的状态变化时 所涉及的功能代码

二 : 监听器的种类

  • 按照被监听的对象划分:ServletRequest域 HttpSession域 ​ServletContext域
  • 监听的内容分:监听域对象的创建与销毁的 监听域对象的属性变​化的
...................................ServletContext域HttpSession域ServletRequest域
域对象的创建于销毁servletContextListenerHttpSessionListenerServletRequestListener
域对象内的属性的变化ServletContextAttributeListenerHttpSessionAttributeListenerServletRequestAttributeListener

三 : 监听三大域对象的创建与销毁的监听器

( 1 )监听ServletContext域的创建与销毁的监听器ServletContextListener

监听编写步骤 :

① : 编写一个监听器类去实现监听器接口

public class MyServletContextListener implements ServletContextListener

② : 覆盖监听器的方法

@Override
    public void contextInitialized(ServletContextEvent sce) {
    System.out.println("context创建了....");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("context销毁了");
    }

③ : 在web.xml中进行配置

<listener>
    <listener-class>com.TianTian.atrribute.MyServletContextAttributeListener</listener-class>
  </listener>

ServletContextListener监听器的主要作用

① : 初始化的工作 ,初始化对象,初始化数据,加载数据驱动,连接池的初始化
② : 加载一下初始化的配置文件,如Spring的配置文件
③ : 任务调度---定时器---Timer/TimerTask

    Timer timer = new Timer();
                //task:任务  firstTime:第一次执行时间  period:间隔执行时间
                //timer.scheduleAtFixedRate(task, firstTime, period);
                
                String currentTime = "2018-10-11 18:11:00";
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                Date parse = null;
                try {
                    parse = format.parse(currentTime);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                timer.scheduleAtFixedRate(new TimerTask() {
                    @Override
                    public void run() {
                        System.out.println("do something.....");
                    }
                } , parse, 24*60*60*1000);

( 2 )监听HttpSession域的创建与销毁的监听器HttpSessionListener

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class MySessionListener implements HttpSessionListener{

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("sessionId : " + se.getSession().getId());
        
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        
    }

}

( 3 )监听ServletRequest域创建与销毁的监听器ServletRequestListener

public class MyServletRequestListener implements ServletRequestListener{

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {

        System.out.println("销毁");
    }
    @Override
    public void requestInitialized(ServletRequestEvent sre) {

        System.out.println("创建");
    }
}

四 : 监听三大域对象的属性变化的

( 1 )域对象的通用方法

  • setAttribute(name,value) 触发添加属性/修改属性的监听器的方法

  • getAttribute(name) 触发获取属性的监听方法

  • removeAttribute(name) 触发删除属性的监听器的方法

( 2 )ServletContextAttributeLisener监听器

public class MyServletContextAttributeListener implements ServletContextAttributeListener{

    @Override
    public void attributeAdded(ServletContextAttributeEvent scab) {

        //放到域中的属性
        System.out.println("+++++监听放入");
        System.out.println(scab.getName());//放到域中的name
        System.out.println(scab.getValue());//放到域中的value
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent scab) {
        System.out.println("+++++监听修改");

        System.out.println(scab.getName());//删除的域中的name
        System.out.println(scab.getValue());//删除的域中的value
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent scab) {
        System.out.println("+++++监听移除");

        System.out.println(scab.getName());//获得修改前的name
        System.out.println(scab.getValue());//获得修改前的value
        
    }

测试

public class TestMyServletContextAttributeListener extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        //存数据
        context.setAttribute("name", "美美");
        //改数据
        context.setAttribute("name", "可可");
        //删除数据
        
        context.removeAttribute("name");
    }   
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doGet(request, response);
    }
}

(3) HttpSessionAttributeListener监听器(同上)

(4) ServletRequestAriibuteListenr监听器(同上)

五 : 对象感知监听器

即将要被绑定到Session中的对象有几种状态

  • 绑定状态 : 就一个对象被放到session域中
  • 解绑状态 : 被绑定的对象从session域中移除了
  • 钝化状态 : 是将session内存中的对象持久化( 序列化)到磁盘
  • 活化状态 : 就是将磁盘上的对象再次恢复到session内存中

(1) 绑定与解绑的监听器HttpSessionBindingListener

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

public class Person implements HttpSessionBindingListener{
    private String id;
    private String name;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    //绑定
    public void valueBound(HttpSessionBindingEvent event) {
        System.out.println("person被绑定了");
                Person per = (Person)event.getValue();
        System.out.println(per.getName());
    }
    @Override
    //解除绑定
    public void valueUnbound(HttpSessionBindingEvent event) {

        System.out.println("person被解绑了");

    }
}

测试

public class TestPersonBindingServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    HttpSession session = request.getSession();
            //将person对象绑到session中
            Person p = new Person();
            p.setId("100");
            p.setName("思思");
            session.setAttribute("person", p);
            //将person对象从session中解绑
            session.removeAttribute("person");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
person被绑定了
思思
person被解绑了

(2) 钝化与活化的监听器HttpSessionActivationListener

可以通过配置文件,指定对象钝化时间---对象多长时间不用被敦化
在META-INF下创建一个context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context>
   <!-- maxIdleSwap:session中的对象多长时间不使用就钝化 -->
   <!-- directory:钝化后的对象的文件写到磁盘的哪个目录下 配置钝化的对象文件在 work/catalina/localhost/钝化文件 -->
   <Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1">
       <Store className="org.apache.catalina.session.FileStore" directory="tiantian" />
   </Manager>
</Context>

创建customer类

public class Customer implements HttpSessionActivationListener,Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private String id;
    private String name;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public void sessionWillPassivate(HttpSessionEvent se) {
        //钝化
        System.out.println("customer被顿化了");
    }
    @Override
    public void sessionDidActivate(HttpSessionEvent se) {
        //激活
        System.out.println("customer被活化了");
    }   
}

测试

ublic class TestCustomerServlet1 extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Customer customer = new Customer();
        customer.setId("200");
        customer.setName("狗狗");
        session.setAttribute("customer", customer);
        System.out.println("customer被放到session域中了");
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}

活化取出

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //从session域中获得customer
                HttpSession session = request.getSession();
                Customer customer = (Customer) session.getAttribute("customer");
                System.out.println(customer.getName());
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ja kar ta

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值