1. 程式人生 > >監聽器Listener

監聽器Listener

odi car schedule zab list time charset xid tee

1.ServletContext監聽器:

用來監聽ServletContext的創建與銷毀

步驟:

a、編寫一個監聽器類去實現監聽器接口

b、覆蓋監聽器的方法

c、需要在web.xml中進行配置---註冊

public class ServletContext implements ServletContextListener {

    public ServletContext() {
        // TODO Auto-generated constructor stub
    }

    public void contextDestroyed(ServletContextEvent sce)  { 
        System.out.println(
"web應用銷毀"); } public void contextInitialized(ServletContextEvent sce) { System.out.println("web應用初始化"); Timer t = new Timer(); t.scheduleAtFixedRate(new TimerTask() {//在ServletContext初始化時,添加定時任務 @Override public void run() { System.out.println(
"利息增加"); } },new Date(), 5000);//執行的任務,開始時間,間隔 } }

2.ServletContextAttributeListener ServletContext屬性監聽

監聽ServletContext中的屬性有變化(增、刪、改)

public class ServletContextAttr implements ServletContextAttributeListener {

    public ServletContextAttr() {
        // TODO Auto-generated constructor stub
} public void attributeAdded(ServletContextAttributeEvent scae) { System.out.println("增加屬性 "); System.out.println("屬性是" + scae.getName()); System.out.println("值是" + scae.getValue()); } public void attributeRemoved(ServletContextAttributeEvent scae) { System.out.println("屬性移除"); } public void attributeReplaced(ServletContextAttributeEvent scae) { System.out.println("屬性替換"); } }
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <%
        application.setAttribute("name","god");//添加ServletContext屬性
        application.setAttribute("name", "wish");//替換屬性
        application.removeAttribute("name");//移除屬性
    %>
</body>
</html>

3.Session監聽器

用來監聽Session的創建與銷毀

public class Session implements HttpSessionListener {

    public Session() {
        // TODO Auto-generated constructor stub
    }

    public void sessionCreated(HttpSessionEvent se)  { 
         String s = se.getSession().getId();
         System.out.println("session被創建,ID為:"+s);
    }

    public void sessionDestroyed(HttpSessionEvent se)  { 
         System.out.println("session被銷毀);
    }
    
}

在線人數統計:

public class OnlineNumberListener implements HttpSessionListener{

    @Override
    public void sessionCreated(HttpSessionEvent e) {
        ServletContext application = e.getSession().getServletContext();
        Integer onlinenumber = (Integer)application.getAttribute("onlinenumber");
        if(onlinenumber==null) {
            onlinenumber = 0;
        }
        onlinenumber++;
        application.setAttribute("onlinenumber", onlinenumber);
        System.out.println("新增一位在線用戶");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent e) {
        ServletContext application = e.getSession().getServletContext();
         
        Integer online_number = (Integer) application.getAttribute("online_number");
 
        if(null==online_number){
            online_number = 0;
        }
        else
            online_number--;
        application.setAttribute("online_number", online_number);
        System.out.println("一位用戶離線");
    }

}

4.Request監聽器

public class Request implements ServletRequestListener {

    public Request() {
        // TODO Auto-generated constructor stub
    }

    public void requestDestroyed(ServletRequestEvent sre)  { 
         System.out.println("請求銷毀");
    }

    public void requestInitialized(ServletRequestEvent sre)  { 
        String p =  sre.getServletRequest().getParameter("name");
        System.out.println("收到請求,請求值為:"+p);
    }
    
}

總結:ServletContext Session Request 都可以實現各自的Listener接口,也可以實現各自的AttributeListener接口,重寫方法即可。

5.綁定監聽

HttpSessionBindingListener接口,可以監聽對象是否被綁定至Session內

public class Person implements HttpSessionBindingListener{
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public void valueBound(HttpSessionBindingEvent event) {
        System.out.println("Person對象綁定至session域");
    }
    @Override
    public void valueUnbound(HttpSessionBindingEvent event) {
        System.out.println("Person對象從session域中解綁");
    }
}
HttpSession session = request.getSession();
Person p = new Person();
session.setAttribute("person", p);
session.removeAttribute("person");

6.鈍化與活化

Session對象長期不使用時可以寫入到本地磁盤,即鈍化,下次訪問時在寫回session中,即活化

需要同時實現HttpSessionActivationListener,Serializable兩個接口

public class Car implements HttpSessionActivationListener,Serializable{
    private static final long serialVersionUID = 1L;
    private String color;
    private String brand;
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public String getBrand() {
        return brand;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }
    @Override
    public void sessionWillPassivate(HttpSessionEvent se) {
        System.out.println("Car被鈍化");
    }
    @Override
    public void sessionDidActivate(HttpSessionEvent se) {
        System.out.println("Car被活化");
    }
}
HttpSession session = request.getSession();
Car c = new Car();
c.setColor("red");
session.setAttribute("car", c);
System.out.println("Car被添加到session中");

自定義配置:

在WebContent/META-INF下創建context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context>
 <!-- maxIdleSwap:session中的對象多長時間不使用就鈍化 -->
 <!-- directory:鈍化後的對象的文件寫到磁盤的哪個目錄下  配置鈍化的對象文件在work/catalina/localhost/鈍化文件 -->
 <Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1">
  <Store className="org.apache.catalina.session.FileStore" directory="demo" />
 </Manager>
</Context>

監聽器Listener