Java监听器Listener

1、Java监听器

监听器用于监听web应用中某些对象、信息的创建、销毁、增加,修改,删除等动作的发生,然后作出相应的响应处理。当范围对象的状态发生变化的时候,服务器自动调用监听器对象中的方法。

2、Java中的事件

Java事件由事件类和监听接口组成,自定义一个事件前,必须提供一个事件的监听接口以及一个事件类。
Java中监听接口是继承java.util.EventListener的类,事件类继承java.util.EventObject的类。
因此Java监听器的组成有三部分:事件源、事件监听器、事件对象。当事件源发生操作时,它会调用事件监听器的一个方法,并且调用这个方法时,会传递事件对象过来。事件监听器是由开发人员编写,开发人员在事件监听器中,通过事件对象可以拿到事件源,从而对事件源上的操作进行处理。

事件监听器接口:

package java.util;

/**
 * A tagging interface that all event listener interfaces must extend.
 * @since JDK1.1
 */
public interface EventListener {
}

事件类:

package java.util;

/**
 * <p>
 * The root class from which all event state objects shall be derived.
 * <p>
 * All Events are constructed with a reference to the object, the "source",
 * that is logically deemed to be the object upon which the Event in question
 * initially occurred upon.
 *
 * @since JDK1.1
 */

public class EventObject implements java.io.Serializable {

    private static final long serialVersionUID = 5516075349620653480L;

    /**
     * The object on which the Event initially occurred.
     */
    protected transient Object  source;

    /**
     * Constructs a prototypical Event.
     *
     * @param    source    The object on which the Event initially occurred.
     * @exception  IllegalArgumentException  if source is null.
     */
    public EventObject(Object source) {
        if (source == null)
            throw new IllegalArgumentException("null source");

        this.source = source;
    }

    /**
     * The object on which the Event initially occurred.
     *
     * @return   The object on which the Event initially occurred.
     */
    public Object getSource() {
        return source;
    }

    /**
     * Returns a String representation of this EventObject.
     *
     * @return  A a String representation of this EventObject.
     */
    public String toString() {
        return getClass().getName() + "[source=" + source + "]";
    }
}

3、Java Web中定义的监听器

JavaWeb开发中的监听器(Listener)就是Application、Session和Request三大对象创建、销毁或者往其中添加、修改、删除属性时自动执行代码的功能组件。

ServletContextListener:对Servlet上下文的创建和销毁进行监听;

ServletContextAttributeListener:监听Servlet上下文属性的添加、删除和替换;

HttpSessionListener:对Session的创建和销毁进行监听。Session的销毁有两种情况,一个中Session超时,还有一种是通过调用Session对象的invalidate()方法使session失效。

HttpSessionAttributeListener:对Session对象中属性的添加、删除和替换进行监听;

ServletRequestListener:对请求对象的初始化和销毁进行监听;

ServletRequestAttributeListener:对请求对象属性的添加、删除和替换进行监听。

4、监听器的用途:

可以使用监听器监听客户端的请求、服务端的操作等。通过监听器,可以自动出发一些动作,比如监听在线的用户数量,统计网站访问量、网站访问监控等。

5、自定义监听器:

定义一个监听用户登录的监听器:

首先定义一个未登录的监听器:UnLoginListenser

import org.springframework.context.ApplicationListener;

/**
 * @Auther: wurong
 * @Date: 2018/7/23 19:58
 * @Description: com.shanghai.abcd.user.web.listener
 */
public class UnLoginListenser implements ApplicationListener<UnLoginEvent> {
    @Override
    public void onApplicationEvent(UnLoginEvent unLoginEvent) {
        unLoginEvent.eventMessage();
    }
}

第二步 定义一个未登录的事件: UnLoginEvent

import com.shanghai.abcd.user.common.utils.Msg;
import com.shanghai.abcd.user.common.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEvent;

/**
 * 未登录事件监听器
 * @Auther: wurong
 * @Date: 2018/7/23 19:53
 * @Description: com.shanghai.abcd.user.web.listener
 */
public class UnLoginEvent<T> extends ApplicationEvent {
    private static final Logger logger = LoggerFactory.getLogger(MyEvent.class);

    public UnLoginEvent(Object source) {
        super(source);
    }
    public Msg<String> eventMessage() {
        return ResultUtil.error(-1,"您还未登录。");

    }
}

第三步 定义事件源:

/**
 * @Auther: wurong
 * @Date: 2018/5/24 21:28
 * @Description: com.shanghai.abcd.user.web.rest
 */

@RestController
@RequestMapping("/test")
public class TestController {
    private static final Logger logger = LoggerFactory.getLogger(TestController.class);
    @Autowired
    private Environment environment;

    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private MyApplicationContextAware myApplicationContextAware;

    @GetMapping("/checkLogin")
    public Msg<String> checkLogin() {
        String str = "您未登录";
        applicationContext.publishEvent(new UnLoginEvent<String>(this));
        return ResultUtil.error(-1,"您未登录");
    }

事件源就是当某一个动作发生的时候进行发布事件,让事件进行调用对应的监听方法进行处理。

原文地址:https://www.cnblogs.com/wrong5566/p/9494583.html