java基礎篇---Servlet監聽器


在寫此篇前,看了一下園友寫的,感覺其基礎知識歸納的十分全面,我在此就不累贅的寫了,鏈接地址(http://www.cnblogs.com/sherryueda/p/4273169.html),

我就寫一下關於監聽器的具體應用:

功能是負責監聽WEB的各種操作,當相關的事件觸發之后將產生事件,並對此事件進行處理,在WEB中可以對application、session、request三種操作進行監聽。 

對application監聽:

對application監聽,實際上就是對ServletContext(Servlet上下文)監聽,主要使用以下兩個接口:ServletContextListener ,ServletContextAttributeListener
package com.oumyye.監聽器;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ServletContextListenerDemo implements ServletContextListener {
    public void contextInitialized(ServletContextEvent event) {    // 上下文初始化時觸發
        System.out.println("** 容器初始化 --> "
                + event.getServletContext().getContextPath());
    }
    public void contextDestroyed(ServletContextEvent event) {        // 上下文銷毀時觸發
        System.out.println("** 容器銷毀 --> "
                + event.getServletContext().getContextPath());
    }
}

web.xml配置

<listener>
    <listener-class>
        com.oumyye.監聽器.ServletContextListenerDemo
    </listener-class>
</listener>

對session監聽 

在監聽器中,針對於session的監聽操作提供了三個接口:HttpSessionListener,HttpSessionAttributeListener,HttpSessionBindingListener
session狀態監聽:HttpSessionListener接口 
  • 當需要對創建或銷毀session的操作進行監聽的時候,可以實現javax.servlet.http.HttpSessionListener接口,此接口定義的方法如下:public void sessionCreated(HttpSessionEvent se),public void sessionDestroyed(HttpSessionEvent se)
  • 當session創建或銷毀后,將產生HttpSessionEvent事件,此事件定義的操作如下:public HttpSession getSession()

對session監聽 

package com.oumyye.監聽器;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class HttpSessionListenerDemo implements HttpSessionListener {
    public void sessionCreated(HttpSessionEvent event) {        // 創建session觸發
        System.out.println("** SESSION創建,SESSION ID = " + event.getSession().getId());
    }
    public void sessionDestroyed(HttpSessionEvent event) {        // 銷毀session觸發
        System.out.println("** SESSION銷毀,SESSION ID = " + event.getSession().getId());
    }
}

web.xml配置

    <listener>
        <listener-class>
                <listener>
        <listener-class>
            com.oumyye.監聽器.HttpSessionListenerDemo
        </listener-class>
    </listener>

session銷毀的操作

當一個新用戶打開一個動態頁時,服務器是會為新用戶分配session,並且觸發HttpSessionListener接口中的sessionCreated()事件,但是在用戶銷毀時卻有兩種不同的方式來觸發sessionDestroyed()事件:
方式一:調用HttpSession接口的invalidate()方法,讓一個session失效。
方式二:超過了配置的session超時時間,session超時時間,可以直接在項目中的web.xml配置。 

session屬性監聽:HttpSessionAttributeListener接口 

在session監聽中也可以對session的屬性操作進行監聽,這一點與監聽上下文屬性的道理是一樣的,要對session的屬性操作監聽,則可以使用javax.servlet.http.HttpSessionAttributeListener接口完成,此接口的方法如下:
public void attributeAdded(HttpSessionBindingEvent se),
public void attributeRemoved(HttpSessionBindingEvent se),
public void attributeReplaced(HttpSessionBindingEvent se)
當進行屬性操作時,將根據屬性的操作觸發HttpSessionAttributeListener接口中的方法,每個操作方法都將產生HttpSessionBindingEvent事件,此事件定義操作如下:
public HttpSession getSession(),
public String getName(),
public Object getValue()
對session的屬性操作監聽 :
package com.oumyye.監聽器;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
public class HttpSessionAttributeListenerDemo implements
        HttpSessionAttributeListener {
    public void attributeAdded(HttpSessionBindingEvent event) {// 屬性增加時調用
        System.out.println(event.getSession().getId() + ",增加屬性 --> 屬性名稱:"
                + event.getName() + ",屬性內容:" + event.getValue());
    }
    public void attributeRemoved(HttpSessionBindingEvent event) {// 屬性刪除時調用
        System.out.println(event.getSession().getId() + ",刪除屬性 --> 屬性名稱:"
                + event.getName() + ",屬性內容:" + event.getValue());
    }
    public void attributeReplaced(HttpSessionBindingEvent event) {// 屬性替換時調用
        System.out.println(event.getSession().getId() + ",替換屬性 --> 屬性名稱:"
                + event.getName() + ",屬性內容:" + event.getValue());
    }
}

web.xml配置

<listener>
    <listener-class>
        com.oumyye.監聽器.HttpSessionAttributeListenerDemo
    </listener-class>
</listener>

session屬性監聽:HttpSessionBindingListener接口 

在session監聽中也可以對session的屬性操作進行監聽,這一點與監聽上下文屬性的道理是一樣的,要對session的屬性操作監聽,則可以使用javax.servlet.http.HttpSessionAttributeListener接口完成:
public void attributeAdded(HttpSessionBindingEvent se)
public void attributeRemoved(HttpSessionBindingEvent se)
public void attributeReplaced(HttpSessionBindingEvent se)
當進行屬性操作時,將根據屬性的操作觸發HttpSessionAttributeListener接口中的方法,每個操作方法都將產生HttpSessionBindingEvent事件
public HttpSession getSession()
public String getName()
public Object getValue() 
對session的屬性操作監聽 
package com.oumyye.監聽器;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
public class HttpSessionAttributeListenerDemo implements
        HttpSessionAttributeListener {
    public void attributeAdded(HttpSessionBindingEvent event) {// 屬性增加時調用
        System.out.println(event.getSession().getId() + ",增加屬性 --> 屬性名稱:"
                + event.getName() + ",屬性內容:" + event.getValue());
    }
    public void attributeRemoved(HttpSessionBindingEvent event) {// 屬性刪除時調用
        System.out.println(event.getSession().getId() + ",刪除屬性 --> 屬性名稱:"
                + event.getName() + ",屬性內容:" + event.getValue());
    }
    public void attributeReplaced(HttpSessionBindingEvent event) {// 屬性替換時調用
        System.out.println(event.getSession().getId() + ",替換屬性 --> 屬性名稱:"
                + event.getName() + ",屬性內容:" + event.getValue());
    }
}

web.xml同上

session屬性監聽:HttpSessionBindingListener接口 

在WEB里也提供了一個javax.servlet.http.HttpSessionBindingListener接口,通過此接口實現的監聽程序可以不用配置而直接使用,此接口定義的方法如下:
public void valueBound(HttpSessionBindingEvent event)
public void valueUnbound(HttpSessionBindingEvent event) 

對request監聽 

在Servlet 2.4之后增加了對request操作的監聽,主要使用ServletRequestListener、ServletRequestAttributeListener兩個接口。 

請求狀態監聽:ServletRequestListener接口

當需要對用戶的每次請求進行監聽的時候,可以使用javax.servlet.ServletRequestListener接口,此接口定義方法如下:
public void requestInitialized(ServletRequestEvent sre)
public void requestDestroyed(ServletRequestEvent sre)
ServletRequestListener接口一旦監聽到事件之后,將產生ServletRequestEvent的事件處理對象,此事件類定義的操作方法如下:
public ServletRequest getServletRequest()
public ServletContext getServletContext()
對用戶請求request監聽 
package com.oumyye.監聽器;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
public class ServletRequestListenerDemo implements ServletRequestListener {
    public void requestInitialized(ServletRequestEvent event) {
        System.out.println("** request初始化。http://"
                + event.getServletRequest().getRemoteAddr()
                + event.getServletContext().getContextPath());
    }
    public void requestDestroyed(ServletRequestEvent event) {
        System.out.println("** request銷毀。http://"
                + event.getServletRequest().getRemoteAddr()
                + event.getServletContext().getContextPath());
    }
}

web.xml配置

<listener>
    <listener-class>
        com.oumyye.監聽器.ServletRequestListenerDemo
    </listener-class>
</listener>

request屬性監聽:ServletRequestAttributeListener接口 

對request范圍屬性的監聽可以使用javax.servlet.ServletRequestAttributeListener接口,此接口定義的方法如下所示:
public void attributeAdded(ServletRequestAttributeEvent srae)
public void attributeReplaced(ServletRequestAttributeEvent srae)
public void attributeRemoved(ServletRequestAttributeEvent srae)
加入監聽器之后request屬性的操作都會產生ServletRequestAttributeEvent事件,此事件的定義的方法如下:
public String getName()
public Object getValue()
監聽request屬性操作 
package com.oumyye.監聽器;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
public class ServletRequestAttributeListenerDemo implements
        ServletRequestAttributeListener {
    public void attributeAdded(ServletRequestAttributeEvent event) {
        System.out.println("** 增加request屬性 --> 屬性名稱:" + event.getName()
                + ",屬性內容:" + event.getValue());
    }
    public void attributeRemoved(ServletRequestAttributeEvent event) {
        System.out.println("** 刪除request屬性 --> 屬性名稱:" + event.getName()
                + ",屬性內容:" + event.getValue());
    }
    public void attributeReplaced(ServletRequestAttributeEvent event) {
        System.out.println("** 替換request屬性 --> 屬性名稱:" + event.getName()
                + ",屬性內容:" + event.getValue());
    }
}

web.xml配置

<listener>
    <listener-class>
        com.oumyye.監聽器.ServletRequestAttributeListenerDemo 
    </listener-class>
</listener>

監聽器實例 —— 在線人員統計 

在線人員列表是一個較為常見的功能,每當用戶登陸成功之后,就會在列表中增加此用戶名稱,這樣就可以知道當前在線的用戶有那些了,這個功能在WEB中只能靠監聽器實現。
使用接口
要完成在線用戶列表的監聽器,需要使用如下幾個接口:
ServletContextListener接口:在上下文初始化時設置一個空的集合到application之中;
HttpSessionAttributeListener接口:用戶增加session屬性時,表示新用戶登陸,從sesion中取出此用戶的登陸名,之后將此用戶保存在列表之中;
HttpSessionListener接口:當用戶注銷(手工注銷、會話超時)將此用戶列表中刪除此用戶。 
代碼過程
創建LoginList.java來存放用戶和在線用戶的具體操作
package com.oumyye.監聽器;

import java.util.*;

public class LoginList {
    private static LoginList user = new LoginList();
    private Vector vector = null;
                         //private調用構造函數,
                         //防止被外界類調用產生新的instance對象  
    public LoginList() {
        this.vector = new Vector();
    }
                        //外界使用的instance對象
    public static LoginList getInstance() {
        return user;
    }
                       //用戶登錄
    public boolean addLoginList(String user) {
        if (user != null) {
            this.vector.add(user);
            return true;
        } else {
            return false;
        }
    }
                        //獲取用戶列表
    public Vector getList() {
        return vector;
    }
                        //刪除用戶
    public void removeLoginList(String user) {
        if (user != null) {
            vector.removeElement(user);
        }
    }
}
LoginList.java

創建LoginNote.java類,實現HttpSessionBindingListener類

package com.oumyye.監聽器;
import javax.servlet.http.HttpSessionBindingEvent;

public class LoginNote implements javax.servlet.http.HttpSessionBindingListener {
  private String user;
  private LoginList container = LoginList.getInstance();
  public LoginNote() {
    user = "";
  }
  public void setUser(String user) {
    this.user = user;
  }
  public String getUser() {
    return this.user;
  }
  public void valueBound(HttpSessionBindingEvent arg0) {
    System.out.println(this.user+"該用戶己經上線" );
  }
  public void valueUnbound(HttpSessionBindingEvent arg0) {
    System.out.println(this.user+"該用戶己經下線");
    if (user != "") {
    container.removeLoginList(user);
    }
  }
}
LoginNote.java

頁面文件

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>監聽查看在線用戶</title>
</head>
<script language="javascript">
function checkEmpty(form){
for(i=0;i<form.length;i++){
if(form.elements[i].value==""){
alert("表單信息不能為空");
return false;
}
}
}
</script>
<link href="css/style.css" rel="stylesheet" type="text/css">
<body>
<div align="center">
  <table width="400" height="150" border="0" cellpadding="0" cellspacing="0" bgcolor="lightblue">
      <Tr><td>&nbsp;</td></Tr>
    <tr>
      <td align="center">
        <form name="form" method="post" action="LoginList.jsp" onSubmit="return checkEmpty(form)">
    <input type="text" name="user"><br><br>
    <input type="submit" name="Submit" value="登錄上線">
  </form>
      </td>
    </tr>
  </table>
</div>
</body>
</html>
index.jsp
<%@ page contentType="text/html; charset=UTF-8" language="java" import="java.sql.*" errorPage="" %>
<%@ page import="java.util.*"%>
<%@ page import="com.oumyye.監聽器.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>監聽查看在線用戶</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
</head>
<%
LoginList list=LoginList.getInstance();
LoginNote ut=new LoginNote();
String name=request.getParameter("user");
ut.setUser(name);
session.setAttribute("list",ut);
list.addLoginList(ut.getUser());
session.setMaxInactiveInterval(10);
%>
<body>
<div align="center">


<table width="400" height="150" border="0" cellpadding="0" cellspacing="0" bgcolor="lightblue">
    <tr align="center"><td>用戶在線列表</td></tr>
  <tr>
    <td align="center"><br>
 
 <textarea rows="5" cols="22">
<%
Vector vector=list.getList();
if(vector!=null&&vector.size()>0){
for(int i=0;i<vector.size();i++){
 out.println(vector.elementAt(i)+"己登錄在線");
}
}
%>
</textarea><br><br>
 <a href="loginOut.jsp">返回</a>
 </td>
  </tr>
</table>
</div>
</body>
</html>
LoginList.jsp
<%@ page contentType="text/html; charset=utf-8" language="java" errorPage="" %>
<%
         session.invalidate();
 out.println("<script>parent.location.href='index.jsp';</script>");
%>
loginOut.jsp

 

 

 


免責聲明!

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



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