1. 程式人生 > 程式設計 >Java Web監聽器Listener介面原理及用法例項

Java Web監聽器Listener介面原理及用法例項

監聽器主要針對三個物件

  • ServletContext
  • HttpSession
  • ServletRequest

使用方式

  • 建立*Listener介面的實現類
  • 在web.xml中註冊該類

在同時註冊多個同介面的監聽器時,執行順序參照web.xml中的註冊順序

  • 監聽器監聽型別
  • 物件的建立和銷燬
  • 物件屬性的新增、替換、移除

建立實現類

// 用於監聽session建立和銷燬的監聽器
package listener;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionListener implements HttpSessionListener {
  @Override
  public void sessionCreated(HttpSessionEvent httpSessionEvent) {
    // 獲取本次事件建立session的id
    String sessionId = httpSessionEvent.getSession().getId();
    System.out.println("create session that id = " + sessionId);
  }

  @Override
  public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
    // 刪除session的id
    String sessionId = httpSessionEvent.getSession().getId();
    System.out.println("session has been destroy that id = " + sessionId);
  }
}

在web.xml中註冊

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     id="WebApp_ID" version="3.1">
 <display-name>Archetype Created Web Application</display-name>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>

 <listener>
 	<!-- 在listener包下的SessionListener類 -->
  <listener-class>listener.SessionListener</listener-class>
 </listener>

</web-app>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。