Javaweb---監聽器

1.什么是監聽器

監聽器就是監聽某個對象的狀態變化的組件。
事件源:被監聽的對象 ----- 三個域對象 request session servletContext
監聽器:監聽事件源對象 事件源對象的狀態的變化都會觸發監聽器 ---- 6+2
注冊監聽器:將監聽器與事件源進行綁定
響應行為:監聽器監聽到事件源的狀態變化時 所涉及的功能代碼 ---- 程序員編寫代 碼

ServletContext域HttpSession域ServletRequest域
域對象內的創建與銷毀ServletContextListenerHttpSessionListenerServletRequestListener
域對象內的屬性的變化ServletContextAttributeListenerHttpSessionAttributeListenerServletRequestAttributeListener
ServletContextListener監聽器的主要作用
a、初始化的工作:初始化對象 初始化數據 ---- 加載數據庫驅動  連接池的初始化
b、加載一些初始化的配置文件 --- spring的配置文件
c、任務調度----定時器----Timer/TimerTask

實現步驟:

1,編寫一個監聽器類去實現監聽器接口

例如創建一個類,類名為:MyServletContextListener

2,覆蓋監聽器的方法(說白了去實現一下ServletContextListener這個接口,并且實現該接口未實現的方法就行)

public class ServletContextListener implements ServletContextListener{//監聽context域對象的創建public void contextInitialized(ServletContextEvent sce) {System.out.println("context創建了...");}//監聽context域對象的銷毀public void contextDestroyed(ServletContextEvent sce) {System.out.println("context銷毀了...");}}

3,需要在web.xml中進行配置—注冊

把該方法的全包名給配置一下即可
<listener><listener-class>beyond.create.MyServletContextListener</listener-class>
</listener>

ServletContextListener
銀行計息:

package beyond.create;import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;public class MyServletContextListener implements ServletContextListener {//實現監聽器接口ServletContext域的創建和銷毀//監聽context域對象的創建public void contextInitialized(ServletContextEvent sce) {//服務器啟動的時候執行該方法System.out.println("context創建了...");//通過sce可以獲得的被監聽的對象//ServletContext servletContext = sce.getServletContext();//就是被監聽的對象---ServletContext//ServletContext source = (ServletContext)sce.getSource();//getSource就是被監聽的對象  是通用方法//開啟一計息任務調度---每天晚上12點計息一次Timer timer = new Timer();//task:任務   firstTime:第一次執行時間  period:間隔執行時間//timer.schedule(task, firstTime, period);/*timer.schedule(new TimerTask() {//TimerTask為一個接口,可以通過匿名內部類進行newpublic void run() {System.out.println("銀行計息了...");}}, new Date(), 5000);*///具體實現銀行計息如下://修改成銀行真實計息業務//1.起始時間:定義成晚上12點//2.間隔時間:24小時SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");String currentTime = "2019-04-29 00:00:00";Date parse = null;try {parse = format.parse(currentTime);//解析字符串} catch (ParseException e) {e.printStackTrace();}timer.schedule(new TimerTask() {@Overridepublic void run() {System.out.println("銀行計息了...");}}, parse, 24*60*60*1000);//一天計息一次}//監聽context域對象的銷毀public void contextDestroyed(ServletContextEvent sce) {System.out.println("context銷毀了...");}}

HttpSessionListener
創建與ServletContextListener一樣,
繼承接口,實現方法,web.xml進行配置
ServletRequestListener也一樣

2,監聽三大域對象的屬性變化

1)域對象的通用方法:
setAttribute(name,value)
—觸發添加屬性的監聽器的方法
—觸發修改屬性的監聽器的方法
getAttribute(name)
removeAttribute(name) - - - 觸發刪除屬性的監聽器的方法

3,對象感知監聽器(與session中的綁定的對象相關的監聽器)

(1)即將要被綁定到session中的對象有幾種狀態
綁定狀態:就一個對象被放到session域中
解綁狀態:就是這個對象從session域中移除了
鈍化狀態:是將session內存中的對象持久化(序列化)到磁盤
活化狀態:就是將磁盤上的對象再次恢復到session內存中

綁定與解綁

首先,HttpSessionBindingListener該監聽器是綁定在對象上的,并且不需要配置web.xml,跟上面綁定監聽器一樣,繼承接口,實現接口未實現的方法

package beyond.domain;import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;public class Person implements HttpSessionBindingListener{//該監聽器是綁到對象身上的,不需要配置web.xmlprivate String id;private String name;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic void valueBound(HttpSessionBindingEvent event) {//綁定的方法System.out.println("Person被綁定了");}@Overridepublic void valueUnbound(HttpSessionBindingEvent event) {//解綁的方法System.out.println("Person被解綁了");}
}
package beyond.domain;import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;public class TestPersonBindingServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {HttpSession session = request.getSession();//先獲得session//將person對象綁定到session中Person p = new Person();p.setId("100");p.setName("beyond");session.setAttribute("person", p);//將p對象(name為person)放到session域當中,被綁定//將person對象從session中解綁session.removeAttribute("person");//跟著name來的}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}
}

鈍化與活化

鈍化與活化的監聽器HttpSessionActivationListener
鈍化:是將session內存中的對象持久化(序列化)到磁盤
活化:就是將磁盤上的對象再次恢復到session內存中
當用戶很多的時候,就需要用鈍化和活化進行優化
與session有關的對象感知監聽器一樣,該監聽器需要綁定在實體上,繼承該監聽器(HttpSessionActivationListener),這里特別注意要實現接口Serializable

public class Customer implements HttpSessionActivationListener,Serializable

例如:創建一個實體Customer,需要繼承HttpSessionActivationListener這個監聽器,并且實現該接口Serializable

package beyond.domain;import java.io.Serializable;import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;public class Customer implements HttpSessionActivationListener,Serializable{//實現這個接口private String id;private String name;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Override//服務器正常關閉時鈍化public void sessionWillPassivate(HttpSessionEvent se) {//鈍化---把session存到磁盤System.out.println("customer被鈍化了");}@Override//服務器再次啟動時活化public void sessionDidActivate(HttpSessionEvent se) {//活化---把磁盤恢復到session內存區域中System.out.println("customer被活化了");}}
鈍化代碼:
package beyond.domain;import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;public class TestCustomerActiveServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {HttpSession session = request.getSession();//獲得session對象Customer customer = new Customer();customer.setId("1014");customer.setName("wsq");session.setAttribute("customer", customer);//將customer放到session當中System.out.println("customer被放到session域中了");//鈍化,已存到本地磁盤中去了}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}
}
活化代碼:
package beyond.domain;import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;public class TestCustomerActiveServlet2 extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//從session域當中獲得customerHttpSession session = request.getSession();//先獲得sessionCustomer customer = (Customer) session.getAttribute("customer");//強轉System.out.println(customer.getName());//活化后輸出customer里面的customer對象的Name值}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}
}
這里需要注意一下:可以通過配置文件 指定對象鈍化時間—對象多長時間不適用被鈍化

在這里插入圖片描述
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"> <!-- 1分鐘不用session被鈍化到磁盤中 --><Store className="org.apache.catalina.session.FileStore" directory="itcast205" />  <!-- 將鈍化后的session存放當itcast205該目錄下,目錄可以自定義 --></Manager>
</Context>
當再次運行Servlet的時候,鈍化后的session會存到相關指定文件夾下

在這里插入圖片描述

該文件夾下面的內容就是session里面的內容

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/379531.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/379531.shtml
英文地址,請注明出處:http://en.pswp.cn/news/379531.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Linux中的Ramdisk和Initrd

Ramdisk簡介先簡單介紹一下ramdisk&#xff0c;Ramdisk是虛擬于RAM中的盤(Disk)。對于用戶來說&#xff0c;能把RAM disk和通常的硬盤分區&#xff08;如/dev/hda1&#xff09;同等對待來使用&#xff0c;例如&#xff1a;redice # mkfs.ext2 /dev/ram0mke2fs 1.38 (30-Jun-200…

slab下kmalloc內核函數實現

文章目錄kmalloc的整體實現獲取高速緩存高速緩存獲取index總結https://blog.csdn.net/qq_41683305/article/details/124554490&#xff0c;在這篇文章中&#xff0c;我們介紹了伙伴算法、slab機制和常見的內存管理函數&#xff0c;接下來&#xff0c;我們看看kmalloc內核函數的…

PHP array_merge_recursive()函數與示例

PHP array_merge_recursive()函數 (PHP array_merge_recursive() function) array_merge_recursive() function is used to merge two or more arrays, it returns a new array with merged elements. The only difference between array_merge() and array_merge_recursive() …

標題:三羊獻瑞

標題&#xff1a;觀察下面的加法算式&#xff1a; 其中&#xff0c;相同的漢字代表相同的數字&#xff0c;不同的漢字代表不同的數字。 請你填寫“三羊獻瑞”所代表的4位數字&#xff08;答案唯一&#xff09;&#xff0c;不要填寫任何多余內容。 思路分析&#xff1a; 首先…

hdu 1069

地址&#xff1a;http://acm.hdu.edu.cn/showproblem.php?pid1069 題意&#xff1a;給定若干個木塊長寬高&#xff0c;長寬高可以自己調整&#xff0c;求堆積起來最高的高度。 mark&#xff1a;枚舉所有木塊長寬高可能情況&#xff0c;簡單dp。 代碼&#xff1a; #include <…

簡明 Python 編程規范

簡明 Python 編程規范編碼 所有的 Python 腳本文件都應在文件頭標上 # -*- coding:utf-8 -*- 。設置編輯器&#xff0c;默認保存為 utf-8 格式。注釋 業界普遍認同 Python 的注釋分為兩種的概念&#xff0c;一種是由 # 開頭的“真正的”注釋&#xff0c;另一種是 docstri…

進程虛擬地址管理

文章目錄1 地址分布實際使用中的內存區域2 進程的虛擬地址描述用戶空間mmap線程之間共享內存地址的實現機制1 地址分布 現在采用虛擬內存的操作系統通常都使用平坦地址空間&#xff0c;平坦地址空間是指地址空間范圍是一個獨立的連續空間&#xff08;比如&#xff0c;地址從0擴…

java兩個文件夾比較路徑_比較Java中兩個文件的路徑

java兩個文件夾比較路徑Given the paths of the two files and we have two compare the paths of the files in Java. 給定兩個文件的路徑&#xff0c;我們有兩個比較Java中文件的路徑。 Comparing paths of two files 比較兩個文件的路徑 To compare the paths of two file…

標題:加法變乘法

標題&#xff1a;我們都知道&#xff1a;123 … 49 1225 現在要求你把其中兩個不相鄰的加號變成乘號&#xff0c;使得結果為2015 比如&#xff1a; 123…10*1112…27*2829…49 2015 就是符合要求的答案。 請你尋找另外一個可能的答案&#xff0c;并把位置靠前的那個乘號左…

C# winform對話框用法大全收藏

對話框中我們常用了以下幾種&#xff1a; 1、文件對話框(FileDialog) 它又常用到兩個&#xff1a; 打開文件對話框(OpenFileDialog) 保存文件對話(SaveFileDialog) 2、字體對話框(FontDialog) 3、顏色對話框(&#xff23;olorDialog) 4、打印預瀏對話框(PrintPreviewDialog) 5、…

【翻譯】eXpressAppFramework QuickStart 業務模型設計(四)—— 實現自定義業務類...

這一講&#xff0c;你將學到如何從頭開始實現業務類。為此&#xff0c;將要實現Department和Position業務類。這些類將被應用到之前實現的Contact類中。你將學到引用對象自動生成用戶界面的基本要素。 在此之前&#xff0c;我建議你去閱讀一下 【翻譯】eXpressAppFramework Qui…

內存重映射

文章目錄1 kmap2 映射內核內存到用戶空間使用remap_pfn_range使用io_remap_pfn_rangemmap文件操作建立VMA和實際物理地址的映射mmap 之前分配 一次性映射mmap 之前分配 Page FaultPage Fault 中分配 映射內核內存有時需要重新映射&#xff0c;無論是從內核到用戶空間還是從內…

math.sqrt 有問題_JavaScript中帶有示例的Math.sqrt()方法

math.sqrt 有問題JavaScript | Math.sqrt()方法 (JavaScript | Math.sqrt() Method) The Math.sqrt() method is inbuilt in JavaScript to find the square root of a number. In this tutorial, we will learn about the sqrt() method with examples. JavaScript中內置了Mat…

標題:移動距離

標題&#xff1a;移動距離 X星球居民小區的樓房全是一樣的&#xff0c;并且按矩陣樣式排列。其樓房的編號為1,2,3… 當排滿一行時&#xff0c;從下一行相鄰的樓往反方向排號。 比如&#xff1a;當小區排號寬度為6時&#xff0c;開始情形如下&#xff1a; 1 2 3 4 5 6 12 11 1…

ISAPI Rewrite 實現簡單url重寫、二級域名重寫

實現步驟&#xff1a; 第一步&#xff1a;下載ISAPI_Rewrite.rar&#xff0c;將Rewrite文件夾和httpd.ini直接放在項目根目錄下面。 第二步&#xff1a;IIS配置&#xff0c;篩選Rewrite文件夾里面的Rewrite.dll文件&#xff0c;如圖&#xff1a; 第三步&#xff1a;在httpd.ini…

用戶登錄

用戶登錄 代碼namespace 用戶登錄 {public partial class Form1 : Form{public Form1(){InitializeComponent();}bool b1, b2, b3, b4, b5, b6;private void button1_Click(object sender, EventArgs e){try{if (b1 && b2 && b3 && b4 && b5 &…

進程上下文和中斷上下文

文章目錄進程的preempt_count變量thread_infopreempt_counthardirq相關softirq相關上下文原文鏈接&#xff1a; https://zhuanlan.zhihu.com/p/88883239進程的preempt_count變量 thread_info 在內核中&#xff0c;上下文的設置和判斷接口可以參考 include/linux/preempt.h 文…

標題:湊算式

標題&#xff1a;湊算式 這個算式中AI代表19的數字&#xff0c;不同的字母代表不同的數字。 比如&#xff1a; 68/3952/714 就是一種解法&#xff0c; 53/1972/486 是另一種解法。 這個算式一共有多少種解法&#xff1f; 注意&#xff1a;你提交應該是個整數&#xff0c;不要…

匯編中imul_JavaScript中帶有示例的Math.imul()方法

匯編中imulJavaScript | Math.imul()方法 (JavaScript | Math.imul() Method) Math.imul() is a function in math library of JavaScript that is used to the 32-bit multiplication of the two values passed to it. It uses C-like semantics to find the multiplication. …

AFTER觸發器與INSTEAD OF觸發器的區別

INSTEAD OF 觸發器用來代替通常的觸發動作&#xff0c;即當對表進行INSERT、UPDATE 或 DELETE 操作時&#xff0c;系統不是直接對表執行這些操作&#xff0c;而是把操作內容交給觸發器&#xff0c;讓觸發器檢查所進行的操作是否正確。如正確才進行相應的操作。因此&#xff0c;…