Java web

JavaWeb Listener

2018-12-30  本文已影响0人  dawsonenjoy

Java Web开发中,监听器常用与监听HttpServletRequest、HttpSession和ServletContext对象,包括创建/销毁、属性变化,还有session绑定JavaBean对象等

监听器创建步骤

1.创建一个类,继承对应的监听器接口
2.重写监听器里面的方法
3.在web.xml文件中对监听器进行注册

监听域对象的创建与销毁接口
1.ServletRequestListener

监听HttpServletRequest对象创建与销毁的接口

2.HttpSessionListener

监听HttpSession对象创建与销毁的接口

3.ServletContextListener

监听ServletContext对象创建与销毁的接口,举例:

package com;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ListenerTest implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("ServletContext初始化..." + sce.getServletContext());
    }
    
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("ServletContext销毁...");
    }
    
}

在web.xml中注册如下:

<listener>
    <listener-class>com.ListenerTest</listener-class>
</listener>

则在打开和关闭tomcat时可以看到初始化和销毁的输出语句

监听域对象属性变化接口

需实现里面的attributeAdded()attributeRemoved()attributeReplaced()接口

1.ServletRequestAttributeListener

监听HttpServletRequest对象属性变化的接口

2.HttpSessionAttributeListener

监听HttpSession对象属性变化的接口,举例:

import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

public class ListenerTest implements HttpSessionAttributeListener {

    public void attributeAdded(HttpSessionBindingEvent se) {
        System.out.println("添加属性:" + se.getName() + "-" + se.getValue() );
    }
    public void attributeRemoved(HttpSessionBindingEvent se) {
        System.out.println("删除属性");
    }
    public void attributeReplaced(HttpSessionBindingEvent se) {
        System.out.println("替换属性");
    }
}

注:
可以看到传入的参数为HttpSessionBindingEvent,即用于监听绑定到Session对象的类,里面有获取这个对象里属性的方法,如getName()/getValue()

3.ServletContextAttributeListener

监听ServletContext对象属性变化的接口

监听JavaBean对象绑定接口

该监听器是绑定在JavaBean对象上的,即对于需要绑定的JavaBean对象来继承该监听器,并且不需要在web.xml中注册

1.HttpSessionBindingListener

监听Session中是否绑定了JavaBean对象接口,举例:

package com.aaa;

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

public class User implements HttpSessionBindingListener {
    private String name;
    private String password;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    public void valueBound(HttpSessionBindingEvent event) {
        System.out.println("User对象被绑定:" + event.getName()); 
    }
    public void valueUnbound(HttpSessionBindingEvent event) {
        System.out.println("User对象解除绑定");   
    }
}
上一篇 下一篇

猜你喜欢

热点阅读