HttpSessionAttributeListener的用法和实例

HttpSessionAttributeListener:
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
HttpSessionAttributeListener能监测到有人正在往HttpSession里添加属性。你可以采取相应的措施。



例 2.2.4.1

package com;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
public class MyHttpSessionAttributeListener implements HttpSessionAttributeListener  {
    public void attributeAdded(HttpSessionBindingEvent arg0) {
        System.out.println("增加了" + arg0.getName() + " " +
                arg0.getValue() );       
    }
    public void attributeRemoved(HttpSessionBindingEvent arg0) {
        System.out.println("去除了" + arg0.getName() + " " +
                arg0.getValue() );
    }
    public void attributeReplaced(HttpSessionBindingEvent arg0) {
        System.out.println("取代了" + arg0.getName() + " " +
                arg0.getValue()+"现在的新值是"+arg0.getSession().getAttribute(arg0.getName()) );
    }
}



web.xml加入下面这段话:


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





用下面这个servlet测试:


package com;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletHello1 extends HttpServlet {
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        System.out.println("add attribute");
        request.getSession().setAttribute("name", "马克-to-win");
        System.out.println("replace attribute");
        request.getSession().setAttribute("name", "mark-to-win");
        System.out.println("remove attribute");
        request.getSession().removeAttribute("name");
    }
}




运行这个servlet以后,console里的输出结果是:

add attribute
增加了name 马克-to-win
replace attribute
取代了name 马克-to-win现在的新值是mark-to-win
remove attribute
去除了name mark-to-win