溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java Web監(jiān)聽器Listener接口是什么

發(fā)布時(shí)間:2020-06-24 09:05:58 來源:億速云 閱讀:157 作者:清晨 欄目:開發(fā)技術(shù)

不懂Java Web監(jiān)聽器Listener接口是什么?其實(shí)想解決這個(gè)問題也不難,下面讓小編帶著大家一起學(xué)習(xí)怎么去解決,希望大家閱讀完這篇文章后大所收獲。

監(jiān)聽器主要針對(duì)三個(gè)對(duì)象

  • ServletContext
  • HttpSession
  • ServletRequest

使用方式

  • 創(chuàng)建*Listener接口的實(shí)現(xiàn)類
  • 在web.xml中注冊(cè)該類
     

在同時(shí)注冊(cè)多個(gè)同接口的監(jiān)聽器時(shí),執(zhí)行順序參照web.xml中的注冊(cè)順序

  • 監(jiān)聽器監(jiān)聽類型
  • 對(duì)象的創(chuàng)建和銷毀
  • 對(duì)象屬性的添加、替換、移除
     

創(chuàng)建實(shí)現(xiàn)類

// 用于監(jiān)聽session創(chuàng)建和銷毀的監(jiān)聽器
package listener;

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

public class SessionListener implements HttpSessionListener {
  @Override
  public void sessionCreated(HttpSessionEvent httpSessionEvent) {
    // 獲取本次事件創(chuàng)建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中注冊(cè)

<&#63;xml version="1.0" encoding="UTF-8"&#63;>
<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>

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享Java Web監(jiān)聽器Listener接口是什么??jī)?nèi)容對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,遇到問題就找億速云,詳細(xì)的解決方法等著你來學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI