温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java中listers的使用方法

发布时间:2020-09-17 10:01:14 来源:亿速云 阅读:115 作者:小新 栏目:编程语言

这篇文章给大家分享的是有关java中listers的使用方法的内容。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。

Java listers是监听器的意思,用于监听Web应用的内部事件的实现类。可以监听用户session的开始与结束,用户请求的到达等等,当事件发生时,会回调监听器的内部方法。

使用Listener步骤

通过实现具体接口创建实现类(可实现多个监听器接口)

配置实现类成为监听器,有两种配置方式:

直接用@WebListener注解修饰实现类

通过web.xml方式配置,代码如下:

<listener>
    <listener-class>com.zrgk.listener.MyListener</lisener-class>
</listener>

常用Web事件监听器接口

1. ServletContextListener

该接口用于监听Web应用的启动与关闭

该接口的两个方法:

contextInitialized(ServletContextEvent event); // 启动web应用时调用
contextDestroyed(ServletContextEvent event); // 关闭web应用时调用

如何获得application对象:

ServletContext application = event.getServletContext();

示例:

@WebListener
public class MyServetContextListener implements ServletContextListener{

    //web应用关闭时调用该方法
    @Override
    public void contextDestroyed(ServletContextEvent event) {
        ServletContext application = event.getServletContext();
        String userName = application.getInitParameter("userName"); 
        System.out.println("关闭web应用的用户名字为:"+userName);
    }

    //web应用启动时调用该方法
    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext application = event.getServletContext();
        String userName = application.getInitParameter("userName");     
        System.out.println("启动web应用的用户名字为:"+userName);
    }

}

2. ServletContextAttributeListener

该接口用于监听ServletContext范围(application)内属性的改变。

该接口的两个方法:

attributeAdded(ServletContextAttributeEvent event);//当把一个属性存进application时触发
attributeRemoved(ServletContextAttributeEvent event);//当把一个属性从application删除时触发
attributeReplaced(ServletContextAttributeEvent event);//当替换application内的某个属性值时触发

如何获得application对象:

ServletContext application = event.getServletContext();

示例:

@WebListener
public class MyServletContextAttributeListener implements ServletContextAttributeListener{

    //向application范围内添加一个属性时触发
    @Override
    public void attributeAdded(ServletContextAttributeEvent event) {
        String name = event.getName();//向application范围添加的属性名
        Object val = event.getValue();      //向application添加的属性对应的属性值
        System.out.println("向application范围内添加了属性名为:"+name+",属性值为:"+val+"的属性");

    }

    //删除属性时触发
    @Override
    public void attributeRemoved(ServletContextAttributeEvent event) {
        // ...      
    }

    //替换属性值时触发
    @Override
    public void attributeReplaced(ServletContextAttributeEvent event) {
        // ...      
    }

}

感谢各位的阅读!关于java中listers的使用方法就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI