監聽器的做用是監聽web容器的有效事件,它由Servlet空器管理,利用Listener接口監聽某個執行程序,並根據該程序的需求作出適應的響應。下面介紹一個應用Servlet監聽實現統計在線人數的實例。javascript
總體結構:css
步驟:html
(1)建立UserInfoList.java類文件,主要用來存儲在線用戶和對在線用戶進行具體操做:java
package com.lixiyu; import java.util.Vector; public class UserInfoList { public static UserInfoList user= new UserInfoList(); @SuppressWarnings("rawtypes") private Vector vector=null; /*利用private調用構造函數, * 防止被外界產生新的instance對象 */ @SuppressWarnings("rawtypes") public UserInfoList(){ this.vector=new Vector(); } //外界使用的instance對象 public static UserInfoList getInstance(){ return user; } //增長用戶 @SuppressWarnings("unchecked") public boolean addUserInfo(String user){ if(user!=null){ this.vector.add(user); return true; }else{ return false; } } //獲取用戶列表 @SuppressWarnings("rawtypes") public Vector getList(){ return vector; } //移除用戶 public void removeUserInfo(String user){ if(user!=null){ vector.removeElement(user); } } }
(2)建立UserInfoTrace.java類文件,主要實現valueBound(HttpSessionBindingEvent arg0)和valueUnbound(HttpSessionBindingEven arg0)兩個方法。當有對象加入session時,valueBound()方法會被自動執行;當有對象從session中移除時,valueUnbound()方法會被自動執行,在valueBound()和valueUnbound()方法中都加入了輸出信息的功能,可以使用戶在控制檯更清楚地瞭解執行過程。web
代碼:sql
package com.lixiyu; import javax.servlet.http.HttpSessionBindingEvent; public class UserInfoTrace implements javax.servlet.http.HttpSessionBindingListener{ private String user; private UserInfoList container=UserInfoList.getInstance(); public UserInfoTrace(){ user=""; } //設置在線監聽人員 public void setUser(String user){ this.user=user; } //獲取在線監聽 public String getUser(){ return this.user; } @Override public void valueBound(HttpSessionBindingEvent arg0) { // TODO Auto-generated method stub System.out.println("上線"+this.user); } @Override public void valueUnbound(HttpSessionBindingEvent arg0) { // TODO Auto-generated method stub System.out.println("下線"+this.user); if(user!=""){ container.removeUserInfo(user); } } }
(3)建立showUser.jsp頁面文件,在頁面中設置session的setMaxInactiveInterval()爲10秒,這樣能夠縮session的生命週期:apache
<%@ page contentType="text/html; charset=UTF-8" language="java" import="java.sql.*" errorPage="" %> <%@ page import="java.util.*"%> <%@ page import="com.lixiyu.*"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>使用監聽查看在線用戶</title> <link href="css/style.css" rel="stylesheet" type="text/css"> </head> <% UserInfoList list=UserInfoList.getInstance(); UserInfoTrace ut=new UserInfoTrace(); String name=request.getParameter("user"); ut.setUser(name); session.setAttribute("list",ut); list.addUserInfo(ut.getUser()); session.setMaxInactiveInterval(10); %> <body> <div align="center"> <table width="506" height="230" border="0" cellpadding="0" cellspacing="0" background="p_w_picpath/background2.jpg"> <tr> <td align="center"><br><br> <textarea rows="8" cols="20"> <% 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>
(4)編寫一個過濾器CharactorFilter確保不會亂碼,編寫MyContentListener實現監聽接口並配置web.xml文件映射。session
CharactorFilterapp
package com.lixiyu; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; // 字符編碼過濾器 public class CharactorFilter implements Filter { // 字符編碼 String encoding = null; @Override public void destroy() { encoding = null; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 判斷字符編碼是否爲空 if(encoding != null){ // 設置request的編碼格式 request.setCharacterEncoding(encoding); // 設置response字符編碼 response.setContentType("text/html; charset="+encoding); } // 傳遞給下一過濾器 chain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { // 獲取初始化參數 encoding = filterConfig.getInitParameter("encoding"); } }
web.xmljsp
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <display-name>web</display-name> <!-- 聲明過濾器 --> <filter> <!-- 過濾器名稱 --> <filter-name>CharactorFilter</filter-name> <!-- 過濾器的完整類名 --> <filter-class>com.lixiyu.CharactorFilter</filter-class> <!-- 初始化參數 --> <init-param> <!-- 參數名 --> <param-name>encoding</param-name> <!-- 參數值 --> <param-value>UTF-8</param-value> </init-param> </filter> <!-- 過濾器映射 --> <filter-mapping> <!-- 過濾器名稱 --> <filter-name>CharactorFilter</filter-name> <!-- URL映射 --> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <description>Added by JBuilder to compile JSPs with debug info</description> <servlet-name>debugjsp</servlet-name> <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class> <init-param> <param-name>classdebuginfo</param-name> <param-value>true</param-value> </init-param> <load-on-startup>3</load-on-startup> </servlet> <servlet-mapping> <servlet-name>debugjsp</servlet-name> <url-pattern>*.jsp</url-pattern> </servlet-mapping> <listener> <listener-class>com.lixiyu.MyContentListener</listener-class> </listener> </web-app>
(5)編寫登錄頁index.jsp和登出頁loginOut.jsp
index.jsp
<%@ page contentType="text/html; charset=UTF-8" 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="506" height="170" border="0" cellpadding="0" cellspacing="0" background="p_w_picpath/background1.jpg"> <tr> <td align="center"> <form name="form" method="post" action="showUser.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>
loginOut.jsp
<%@ page contentType="text/html; charset=UTF-8" language="java" errorPage="" %> <% session.invalidate(); out.println("<script>parent.location.href='index.jsp';</script>"); %>
最後運行本實例,結果如圖所示:
當輸入爲空會提示: