Java中HttpSessionAttributeListener监听器详解

HttpSessionAttributeListener是对session的属性(添加,删除,替换)进行监听。

方法

public void attributeAdded(HttpSessionBindingEvent se);//增加属性
public void attributeRemoved(HttpSessionBindingEvent se);//删除属性
public void attributeReplaced(HttpSessionBindingEvent se);//替换属性

//HttpSessionBindingEvent事件:
public String getName();//取得属性的名称
public Object getValue();//取得属性的值
public HttpSession getSession();//取得当前的session

例子

//MyAttributeListener.java
package com.test;   
import javax.servlet.http.HttpSessionAttributeListener;  
import javax.servlet.http.HttpSessionBindingEvent;  
public class MyAttributeListener implements HttpSessionAttributeListener {  
    @Override  
    public void attributeAdded(HttpSessionBindingEvent event) {  
        String attributeName = event.getName();  
        Object attributeValue = event.getValue();  
        System.out.println("HttpSessionAttributeListener Attribute added : " + attributeName + " : "  
                + attributeValue);  
    }  
  
    @Override  
    public void attributeRemoved(HttpSessionBindingEvent event) {  
        String attributeName = event.getName();  
        Object attributeValue = event.getValue();  
        System.out.println("HttpSessionAttributeListener Attribute removed : " + attributeName + " : "  
                + attributeValue);  
    }  
  
    @Override  
    public void attributeReplaced(HttpSessionBindingEvent event) {  
        String attributeName = event.getName();  
        Object attributeValue = event.getValue();  
        System.out.println("Attribute replaced : " + attributeName + " : "  
                + attributeValue);  
    }  
}  
//web.xml配置监听器
<listener>  
    <listener-class>com.test.MyAttributeListener</listener-class>  
</listener>  
//test.jsp
<html>
<body>  
    <%  
        session = request.getSession();  
        session.setAttribute("url", "51gjie.com"); //HttpSessionAttributeListener attributeAdded() is executed  
        session.setAttribute("url", "www.51gjie.com"); //attributeReplaced() is executed  
        session.removeAttribute("url"); //HttpSessionAttributeListener attributeRemoved() is executed  
    %>  
</body>  
</html>  

版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。