java web Listener的簡單使用案例


1、web.xml的配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 3     xmlns="http://java.sun.com/xml/ns/javaee" 
 4     xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
 6     <display-name>testServletListener</display-name>
 7     <listener>
 8         <listener-class>test_servlet_package.MyRequestListener</listener-class>
 9     </listener>
10     <listener>
11         <listener-class>test_servlet_package.MySessionListener</listener-class>
12     </listener>
13     <listener>
14         <listener-class>test_servlet_package.MyServletContextListener</listener-class>
15     </listener>
16     <!-- 配置歡迎界面 -->
17     <welcome-file-list>
18         <welcome-file>index.jsp</welcome-file>
19     </welcome-file-list>
20 </web-app>

2、RequestListener

 1 package test_servlet_package;
 2 import java.io.FileOutputStream;
 3 import java.io.PrintWriter;
 4 import javax.servlet.ServletRequest;
 5 import javax.servlet.ServletRequestAttributeEvent;
 6 import javax.servlet.ServletRequestAttributeListener;
 7 import javax.servlet.ServletRequestEvent;
 8 import javax.servlet.ServletRequestListener;
 9 /*
10 Servlet事件監聽器
11 在Servlet技術中已經定義了一些事件,
12 並且我們可以針對這些事件來編寫相關的事件監聽器,從而對事件作出相應處理。
13 Servlet事件主要有3類:Servlet上下文事件、會話事件與請求事件
14 下面具體講解這3類事件的監聽器實現。
15 
16 1.對Servlet上下文進行監聽
17 可以監聽ServletContext對象的創建和刪除以及屬性的添加、刪除和修改等操作。該監聽器需要使用到如下兩個接口類:
18     ● ServletContextAttributeListener:監聽對ServletContext屬性的操作,如增加、刪除、修改操作。
19     ● ServletContextListener:監聽ServletContext,
20         當創建ServletContext時,激發contextInitialized (ServletContextEvent sce)方法。
21         當銷毀ServletContext時,激發contextDestroyed(ServletContext- Event sce)方法。
22 
23 2.監聽Http會話
24 可以監聽Http會話活動情況、Http會話中屬性設置情況,也可以監聽Http會話的active、paasivate情況等。該監聽器需要使用到如下多個接口類:
25   ● HttpSessionListener:監聽HttpSession的操作。
26         當創建一個Session時,激發session Created (SessionEvent se)方法;
27         當銷毀一個Session時,激發sessionDestroyed (HttpSessionEvent se)方法。
28   ● HttpSessionActivationListener:用於監聽Http會話active、passivate情況。
29   ● HttpSessionAttributeListener:監聽HttpSession中屬性的操作。
30         當在Session增加一個屬性時,激發attributeAdded(HttpSessionBindingEvent se) 方法;
31         當在Session刪除一個屬性時,激發attributeRemoved(HttpSessionBindingEvent se)方法;
32         當在Session屬性被重新設置時,激發attributeReplaced(HttpSessionBindingEvent se) 方法。
33       
34 3.對客戶端請求進行監聽
35 對客戶端的請求進行監聽是在Servlet 2.4規范中新添加的一項技術,使用的接口類如下:
36     ● ServletRequestListener接口類。
37     ● ServletRequestAttrubuteListener接口類
38   
39 */
40 public class MyRequestListener implements ServletRequestListener,ServletRequestAttributeListener{
41     public void requestDestroyed(ServletRequestEvent arg0) {
42         //對銷毀客戶端請求進行監聽
43         print("reqeust destroyed");
44     }
45     public void requestInitialized(ServletRequestEvent arg0) {
46         //對實現客戶端請求進行監聽
47         print("Request init");
48         ServletRequest sr = arg0.getServletRequest(); //初始化客戶端請求
49         print(sr.getRemoteAddr()); //獲得請求客戶端的地址
50     }
51     public void attributeAdded(ServletRequestAttributeEvent arg0) {
52         //對屬性的添加進行監聽
53         print("attributeAdded('"+arg0.getName()+"','"+arg0.getValue()+"')");
54     }
55     public void attributeRemoved(ServletRequestAttributeEvent arg0) {
56         //對屬性的刪除進行監聽
57         print("attributeRemoved('"+arg0.getName()+"','"+arg0.getValue()+"')");
58     }
59     public void attributeReplaced(ServletRequestAttributeEvent arg0) {
60         //對屬性的更新進行監聽
61         print("attributeReplaced('"+arg0.getName()+"','"+arg0.getValue()+"')");
62     }
63     private void print(String message){
64         //調用該方法在txt文件中打印出message字符串信息
65         PrintWriter out = null;
66         try{
67              out = new PrintWriter(new FileOutputStream("d:\\output.txt",true));
68              out.println(new java.util.Date()+" RequestListener: "+message);
69              out.close();
70         }catch(Exception e){
71             e.printStackTrace();
72         }
73     }
74 /*
75 對客戶端請求進行監聽的技術是在Servlet 2.4版本之后才出現的。一旦監聽程序能夠獲得客戶端請求,
76 就可以對所有客戶端請求進行統一處理。例如,一個Web程序如果在本機訪問,就可以不登錄,如果是遠程訪問,
77 即需要登錄。這是通過監聽客戶端請求,從請求中獲取到客戶端地址,並通過地址來作出相應的處理。
78 程序說明:該監聽器類實現了ServletRequestListener和ServletRequestAttributeListener兩接口類,
79 ServletRequestListener接口類中定義的兩個方法對客戶端請求的創建和銷毀進行監聽;
80 ServletRequestAttributeListener接口類對請求中的屬性添加、修改和刪除進行監聽。
81 *
82 */
83 }
View Code

3、ServletContextListener

 1 package test_servlet_package;
 2 
 3 import java.io.FileOutputStream;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletContext;
 7 import javax.servlet.ServletContextAttributeEvent;
 8 import javax.servlet.ServletContextAttributeListener;
 9 import javax.servlet.ServletContextEvent;
10 import javax.servlet.ServletContextListener;
11 
12 public class MyServletContextListener implements ServletContextListener,ServletContextAttributeListener{
13     private ServletContext context = null; //定義一個ServletContext對象變量,賦為null  
14     public void contextInitialized(ServletContextEvent s) {
15         //TODO 該方法實現了ServletContextListener接口定義的方法,對ServletContext進行初始化  
16         this.context = s.getServletContext(); //初始化一個ServletContext對象  
17         print("ServletContext初始化......"); //打印出該方法的操作信息
18     }  
19     public void contextDestroyed(ServletContextEvent s) {
20         //TODO 該方法實現了ServletContextListener接口類定義方法,用於釋放ServletContext對象  
21         this.context = null;
22         print("ServletContext被釋放......");
23     }  
24     public void attributeAdded(ServletContextAttributeEvent sa) {
25         //TODO 當上下文添加屬性時,將調用該方法。這里只是將添加的屬性信息打印出來
26         print("增加ServletContext對象的一個屬性:attributeAdded('"+sa.getName()+"',' "+sa.getValue()+"')");
27     }  
28     public void attributeRemoved(ServletContextAttributeEvent sa) {
29         //TODO 當把ServletContext中的某個屬性刪除時,調用該方法  
30         print("刪除ServletContext對象的某一個屬性:attributeRemoved('"+sa.getName()+"'");  
31     }  
32     public void attributeReplaced(ServletContextAttributeEvent sa) {
33         //TODO 當上下文進行屬性值更新時,將調用該方法  
34         print("更改ServletContext對象的某一個屬性:attributeReplaced('"+sa.getName()+"','"+sa.getValue()+"')");
35     }          
36     private void print(String message){
37         //調用該方法在txt文件中打印出message字符串信息  
38         PrintWriter out = null;  
39         try{ 
40             out = new PrintWriter(new FileOutputStream("D:\\output.txt",true));  
41             out.println(new java.util.Date()+" ContextListener: "+message);
42             out.close();
43         }catch(Exception e){  
44             e.printStackTrace();
45         }
46     }
47 /*
48     程序說明:該監聽器類實現了ServletContextAttributeListener和ServletContextListener兩個接口類中的5個方法:
49         ● contextInitialized(ServletContextEvent s)方法用來初始化ServletContext對象。
50         ● contextDestroyed(ServletContextEvent s)方法在上下文中刪除某個屬性時調用。
51         ● attributeAdded(ServletContextAttributeEvent sa)方法在上下文中添加一個新的屬性時調用。
52         ● attributeReplaced(ServletContextAttributeEvent sa)方法在更新屬性時調用。
53         ● attributeRemoved(ServletContextAttributeEvent sa)方法在上下文中刪除某個屬性時會被調用。
54     在使用這個監聽器之前還需要在Web模塊中的web.xml配置文件中進行聲明,代碼如下:
55     <listener>
56         <listener-class>servlet.MyServletContextListener</listener-class>
57     </listener>
58  * */
59 
60 
61 }
View Code

4、SessionBindingListener

 1 package test_servlet_package;
 2 
 3 import javax.servlet.http.HttpSessionBindingEvent;
 4 import javax.servlet.http.HttpSessionBindingListener;
 5 
 6 public class MySessionBindingListener implements HttpSessionBindingListener{
 7 
 8     @Override
 9     public void valueBound(HttpSessionBindingEvent arg0) {
10         // TODO Auto-generated method stub
11         System.out.println(arg0.getName() + arg0.getValue());
12     }
13 
14     @Override
15     public void valueUnbound(HttpSessionBindingEvent arg0) {
16         // TODO Auto-generated method stub
17         System.out.println(arg0.getName() + arg0.getValue());
18     }
19 
20 }
View Code

5、SessionListener

 1 package test_servlet_package;
 2 import java.io.FileOutputStream;
 3 import java.io.PrintWriter;
 4 import javax.servlet.ServletContext;
 5 import javax.servlet.ServletContextEvent;
 6 import javax.servlet.ServletContextListener;
 7 import javax.servlet.http.HttpSessionActivationListener;
 8 import javax.servlet.http.HttpSessionAttributeListener;
 9 import javax.servlet.http.HttpSessionBindingEvent;
10 import javax.servlet.http.HttpSessionEvent;
11 import javax.servlet.http.HttpSessionListener;
12 public class MySessionListener implements HttpSessionActivationListener,HttpSessionAttributeListener,HttpSessionListener,ServletContextListener{
13     ServletContext context = null;
14     int users = 0;
15     public void sessionWillPassivate(HttpSessionEvent arg0) {
16         //監聽Http會話的passivate情況
17         print("sessionWillPassivate("+arg0.getSession().getId()+")");
18     }
19     public void sessionDidActivate(HttpSessionEvent arg0) {
20         //監聽Http會話的active情況
21         print("sessionDidActivate("+arg0.getSession().getId()+")");
22     }
23     public void attributeAdded(HttpSessionBindingEvent arg0) {
24         //監聽Http會話中的屬性添加
25         print("attributeAdded('"+arg0.getSession().getId()+"','"+arg0.getName()+"','"+arg0.getValue()+"')");
26     }
27     public void attributeRemoved(HttpSessionBindingEvent arg0) {
28         //監聽Http會話中的屬性刪除
29         print("attributeRemoved('"+arg0.getSession().getId()+"','"+arg0.getName()+"','"+arg0.getValue()+"')");
30     }
31     public void attributeReplaced(HttpSessionBindingEvent arg0) {
32         //監聽Http會話中的屬性更改操作
33         print("attributeReplaced('"+arg0.getSession().getId()+"','"+arg0.getName()+"','"+arg0.getValue()+"')");
34     }  
35     public void sessionCreated(HttpSessionEvent arg0) {
36         //Http會話的創建監聽
37         users++; //創建一個會話,把users變量加1
38         print("sessionCreated('"+arg0.getSession().getId()+"'),目前擁有"+users+"個用戶");
39         context.setAttribute("users",new Integer(users)); //把會話數設置到ServletContext的屬性users中
40     }
41     public void sessionDestroyed(HttpSessionEvent arg0) {
42         //Http會話的釋放監聽
43         users--;//釋放一個會話,把users變量減1
44         print("sessionDestroyed('"+arg0.getSession().getId()+"'),目前擁有"+users+"個用戶");
45         context.setAttribute("users",new Integer(users));        //把會話數設置到ServletContext的屬性users中
46     }
47     public void contextInitialized(ServletContextEvent arg0) {
48         //該方法實現了ServletContextListener接口定義的方法,對ServletContext進行初始化
49         this.context = arg0.getServletContext();//初始化ServletContext對象
50         print("ServletContext初始化......");//打印出該方法的操作信息
51     }
52     public void contextDestroyed(ServletContextEvent arg0) {
53         //監聽Servlet上下文被釋放
54         this.context = null; //釋放ServletContext對象
55         print("ServletContext被釋放......");//打印出該方法的操作信息
56     }
57     private void print(String message){
58         //調用該方法在txt文件中打印出message字符串信息
59         PrintWriter out = null;
60         try{
61             out = new PrintWriter(new FileOutputStream("d:\\output.txt",true));
62             out.println(new java.util.Date()+" SessionListener: "+message);
63             out.close();
64         }catch(Exception e){
65             e.printStackTrace();
66         }
67     }
68 /*
69     (1)該程序實現了HttpSessionListener接口類中的兩個方法:
70         ● sessionCreated(HttpSessionEvent arg0)方法進行Http會話創建的監聽,如果Http會話被創建將調用該方法。
71         ● sessionDestroyed(HttpSessionEvent arg0)方法對Http會話銷毀進行監聽,如果某個Http會話被釋放將調用該方法。
72     (2)實現HttpSessionActivationListener接口類中的如下兩個方法:
73         ● sessionDidActivate(HttpSessionEvent arg0)方法對Http會話處於active情況進行監聽。
74         ● sessionWillPassivate(HttpSessionEvent arg0)方法對Http會話處於passivate情況進行監聽。
75     (3)實現HttpSessionAttributeListener接口類中的如下3種方法:
76         ● attributeAdded(HttpSessionBindingEvent arg0)方法對Http會話中屬性添加進行監聽。
77         ● attributeReplaced(HttpSessionBindingEvent arg0)方法對Http會話中屬性修改進行監聽。
78         ● attributeRemoved(HttpSessionBindingEvent arg0)方法對Http會話中屬性刪除進行監聽。
79     (4)另外,該程序中還實現了ServletContextListener接口類,該類的實現方法已經在12.2.1小節中有所介紹。
80         同樣需要在web.xml配置文件進行該監聽器的聲明,該監聽器實現了在線會話人數的統計,
81         當一個會話創建時,users變量將加1;當銷毀一個會話對象的時候,users變量將減1。
82 */
83 
84 }
View Code

6、測試

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%@ page import="test_servlet_package.MySessionBindingListener"%>
 3 <%@ page import="java.util.*"%>
 4 <html>
 5 <head>
 6     <title>index.jsp</title>
 7 </head>
 8 <body>
 9     <%
10         out.println("Test ServletContextListener");
11         application.setAttribute("userid", "zzb"); //添加一個屬性  
12         application.setAttribute("userid", "zzb2"); //替換掉已經添加的屬性  
13         application.removeAttribute("userid"); //刪除該屬性
14     %>
15     <%
16         out.println("Test SessionListener");
17         session.setAttribute("username", "zzb1"); //在Http會話中設置一個用戶username屬性  
18         session.setAttribute("username", "zzb2"); //修改之上添加的username屬性  
19 
20         session.removeAttribute("username"); //刪除創建的username屬性  
21         MySessionBindingListener mySessionBindingListener = new MySessionBindingListener();
22         session.setAttribute("onlineUserListener", mySessionBindingListener);
23 
24         session.invalidate(); //passivate Http會話
25     %>
26     <%
27         out.println("Test RequestListener");
28         request.setAttribute("username", "zzb1"); //在請求中設置一個用戶username屬性
29         request.setAttribute("username", "zzb2"); //修改之上添加的username屬性
30         request.removeAttribute("username");
31     %>
32 </body>
33 </html>

總結:測試監聽器的小案例、方便查詢復習


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM