zoukankan      html  css  js  c++  java
  • Servlet监听器——实现在线登录人数统计小例子

    一、概念

    servlet监听器的主要目的是给web应用增加事件处理机制,以便更好的监视和控制web应用的状态变化,从而在后台调用相应处理程序。

    二、监听器的类型

    1.根据监听对象的类型和范围,分为3类

    Request事件监听器

    HttpSession事件监听器

    ServletContext事件监听器

    2.八个监听接口和六个监听事件

    三、ServletContext监听

    1.Application对象

    application是ServletContext的实例,由JSP容器默认创建。Servlet中调用getServletContext()方法得到ServletContext的实例。

    全局对象即Application范围的对象,初始化阶段的变量值在web.xml中,经由<context-param>元素所设定的变量,它的范围也是Application的范围

    2.ServletContextListener接口

    用于监听Web应用启动和销毁的事件,监听器类需要实现ServletContextListener接口。

    该接口的主要方法;

    void contextInitialized(ServletContextEvent se):通知正在接受的对象,应用程序已经被加载及初始化

    void contextDestroyed(ServletContextEvent se):通知正在接受的对象,应用程序已经被销毁

    ServletContextEvent的主要方法:ServletContext getServletContext():取得当前的ServletContext对象

    3.ServletContextAttributeListener

    用于监听Web应用属性改变的事件,包括增加、删除、修改属性。监听器类需要实现ServletContextAttributeListener接口

    ServletContextAttributeListener接口的主要方法:

    void attributeAdded(ServletContextAttributeEvent se):若有对象加入Application的范围,通知正在收听的对象。

    void attributeRemoved(ServletContextAttributeEvent se):若有对象从Application范围移除,通知正在收听的对象。

    void attributeReplaced(ServletContextAttributeEvent se):若在Application的范围中,有对象取代另一个对象时,通知正在收听的对象

    ServletContextAttributeEvent中的主要方法:

    getName():返回属性名称

    getValue()返回属性的值

    四、HttpSession 会话监听

    1.HttpSessionListener

    主要方法:

    sessionCreated(HttpSessionEvent se):session创建

    sessionDestroyed(HttpSessionEvent se):session销毁

    2.HttpSessionActivationListener:

    监听器监听Http会话的情况

    3.HttpSessionAttributeListener:

    监听HttpSession中属性的操作

    该接口的主要方法:

    void attributeAdded(HttpSessionBindingEvent se):监听Http会话中的属性添加

    void attributeRemoved(HttpSessionBindingEvent se):监听Http会话中的属性移除

    void attributeReplaced(HttpSessionBindingEvent se):监听Http会话中的属性更改操作

    4.HttpSessionBindingListener

    监听Http会话中对象的绑定信息

    getSession():获取session对象

    getName():返回session增加、删除、或替换的属性名称

    getValue():返回session增加、删除、或替换的属性值

    五、ServletRequest监听

    可以监听客户端的请求

    1.ServletRequestListener接口

    用于监听客户端的请求初始化和销毁事件,需要实现ServletRequestListener接口
    接口中的方法:
    requestInitialized(ServletRequestEvent):通知当前对象请求已经被加载及初始化
    requestDestroyed(ServletRequestEvent):通知当前对象,请求已经被消除
    ServletRequestEvent实例中的方法
    getServletRequest():获取ServletRequest对象
    getServletContext():获取ServletContext对象
    2.ServletRequestAttributeListener
    用于监听Web应用属性改变的事件,包括增加属性、删除属性、修改属性
    接口方法:
    void attributeAdded(ServletRequestAttributeEvent e):向Request对象添加新属性
    void attributeRemoved(ServletRequestAttributeEvent e):从request对象中删除属性
    void attributeReplaced(ServletRequestAttributeEvent e):替换对象中现有属性值
    ServletRequestAttributeEvent中的主要方法:
    getName():返回Request增加、删除、或替换的属性名称
    getValue():返回Request增加、删除、或替换的属性的值

    六、存储在线用户信息的例子

    1.login.jsp页面实现用户登录

    [html] view plain copy
     
    1. <body>  
    2.     <form method="get" action="logindo">  
    3.         <center>  
    4.             <h2>用户登录</h2>  
    5.             <hr />  
    6.             <br /> 用户名: <input type="text" name="userName" /> <br />   
    7.             <input type="submit" value="登录" />  
    8.         </center>  
    9.     </form>  
    10. </body>  

    2.建立存储用户信息的类:UserList.java

    [java] view plain copy
     
    1. package listener;  
    2.   
    3. import java.util.Vector;  
    4.   
    5. public class UserList {  
    6.     private static Vector online = new Vector();  
    7.     //添加在线人数  
    8.     public static void addUser(String userName){  
    9.         online.addElement(userName);  
    10.     }  
    11.     //移除在线人数  
    12.     public static void removeUser(String userName){  
    13.         online.removeElement(userName);  
    14.     }  
    15.     //获取在线用户数量  
    16.     public static int getUserCount(){  
    17.         return online.size();  
    18.     }  
    19.     public static Vector getVector(){  
    20.         return online;  
    21.     }  
    22. }  


    ****Vector 类提供了实现可增长数组的功能,随着更多元素加入其中,数组变的更大。在删除一些元素之后,数组变小。 

    Vector 有三个构造函数, 
    public Vector(int initialCapacity,int capacityIncrement)  

    public Vector(int initialCapacity)

    public Vector()   

    Vector 运行时创建一个初始的存储容量initialCapacity,存储容量是以capacityIncrement 变量定义的增量增长。初始的存储容量和capacityIncrement 可以在Vector 的构造函数中定义。第二个构造函数只创建初始存储容量。第三个构造函数既不指定初始的存储容量也不指定capacityIncrement。   

    Vector 类提供的访问方法支持类似数组运算和与Vector 大小相关的运算。类似数组的运算允许向量中增加,删除和插入元素。

    ****

    3.写监听器类

    [java] view plain copy
     
    1. package listener;  
    2.   
    3. import javax.servlet.http.HttpSessionAttributeListener;  
    4. import javax.servlet.http.HttpSessionBindingEvent;  
    5. import javax.servlet.http.HttpSessionEvent;  
    6. import javax.servlet.http.HttpSessionListener;  
    7.   
    8. public class OnlineListener implements HttpSessionListener,HttpSessionAttributeListener{  
    9.     //监听Http会话中的属性添加  
    10.     public void attributeAdded(HttpSessionBindingEvent se) {  
    11.         // TODO Auto-generated method stub  
    12.         UserList.addUser(String.valueOf(se.getValue()));//增加一个用户  
    13.         System.out.println("session("+se.getSession().getId()+")增加属性"+se.getName()+",值为"+se.getValue());  
    14.     }  
    15.     //监听Http会话中的属性移除  
    16.     public void attributeRemoved(HttpSessionBindingEvent se) {  
    17.         // TODO Auto-generated method stub  
    18.         UserList.removeUser(String.valueOf(se.getValue()));  
    19.         System.out.println(se.getValue()+"属性已移除");  
    20.     }  
    21.     //监听Http会话中的属性更改操作  
    22.     public void attributeReplaced(HttpSessionBindingEvent se) {  
    23.         // TODO Auto-generated method stub  
    24.         String oldValue=String.valueOf(se.getValue());//旧的属性  
    25.         String newValue=String.valueOf(se.getSession().getAttribute(se.getName()));//新的属性  
    26.         UserList.removeUser(oldValue);//移除旧的属性  
    27.         UserList.addUser(newValue);//增加新的属性  
    28.         System.out.println(oldValue+"属性已更改为"+newValue);  
    29.     }  
    30.   
    31.     public void sessionCreated(HttpSessionEvent se) {  
    32.         // TODO Auto-generated method stub  
    33.         System.out.println("会话已创建!");  
    34.     }  
    35.   
    36.     public void sessionDestroyed(HttpSessionEvent se) {  
    37.         // TODO Auto-generated method stub  
    38.         System.out.println("会话已销毁!");  
    39.     }  
    40.   
    41. }  

    4.建立用户登录类LoginServlet.java

    [java] view plain copy
     
    1. package listener;  
    2.   
    3. import java.io.IOException;  
    4.   
    5. import javax.servlet.ServletException;  
    6. import javax.servlet.http.HttpServlet;  
    7. import javax.servlet.http.HttpServletRequest;  
    8. import javax.servlet.http.HttpServletResponse;  
    9. import javax.servlet.http.HttpSession;  
    10.   
    11. public class LoginServlet extends HttpServlet{  
    12.     @Override  
    13.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
    14.             throws ServletException, IOException {  
    15.         // TODO Auto-generated method stub  
    16.         String userName=req.getParameter("userName");//获取前台传来的userName属性  
    17.         HttpSession session = req.getSession();  
    18.         session.setAttribute("userName", userName);//将属性保存到session会话中  
    19.         resp.sendRedirect("index.jsp");//重定向到index.jsp页面  
    20.     }  
    21.     @Override  
    22.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
    23.             throws ServletException, IOException {  
    24.         // TODO Auto-generated method stub  
    25.         doGet(req, resp);  
    26.     }  
    27. }  

    5.建立退出登录类

    [java] view plain copy
     
    1. package listener;  
    2.   
    3. import java.io.IOException;  
    4.   
    5. import javax.servlet.ServletException;  
    6. import javax.servlet.http.HttpServlet;  
    7. import javax.servlet.http.HttpServletRequest;  
    8. import javax.servlet.http.HttpServletResponse;  
    9.   
    10. public class ExitServlet extends HttpServlet{  
    11.     @Override  
    12.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
    13.             throws ServletException, IOException {  
    14.         // TODO Auto-generated method stub  
    15.         req.getSession().removeAttribute("userName");//从session中移除对象  
    16.         resp.sendRedirect("login.jsp");//重定向到用户登录页面  
    17.     }  
    18.     @Override  
    19.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
    20.             throws ServletException, IOException {  
    21.         // TODO Auto-generated method stub  
    22.         doGet(req, resp);  
    23.     }  
    24. }  

    6.在web.xml中配置监听器、登录和退出的Servlet

    [html] view plain copy
     
    1. <!-- 配置监听器 -->  
    2. <listener>  
    3.     <listener-class>listener.OnlineListener</listener-class>  
    4. </listener>     
    5. <!-- 配置servlet -->  
    6. <servlet>  
    7.     <servlet-name>LoginServlet</servlet-name>  
    8.     <servlet-class>listener.LoginServlet</servlet-class>  
    9. </servlet>  
    10. <servlet>  
    11.     <servlet-name>ExitServlet</servlet-name>  
    12.     <servlet-class>listener.ExitServlet</servlet-class>  
    13. </servlet>  
    14. <servlet-mapping>  
    15.     <servlet-name>LoginServlet</servlet-name>  
    16.     <url-pattern>/logindo</url-pattern>  
    17. </servlet-mapping>  
    18. <servlet-mapping>  
    19.     <servlet-name>ExitServlet</servlet-name>  
    20.     <url-pattern>/exitdo</url-pattern>  
    21. </servlet-mapping>  

    7.编写index.jsp在线首页

    [html] view plain copy
     
      1. <body>  
      2.     <%  
      3.         //如果未登录,转向登录页面  
      4.         if (session.getAttribute("userName") == null) {  
      5.             response.sendRedirect("login.jsp");  
      6.         }  
      7.         Vector onlineUsers = UserList.getVector(); //获取存储在线用户名的vector对象  
      8.     %>  
      9.     <center>  
      10.         <br />  
      11.         <br />  
      12.         <h2>登录成功</h2>  
      13.         <hr />  
      14.         <br /> 欢迎你 <span style="color:red;"<%=session.getAttribute("userName")%>  
      15.         </span>      <href="exitdo">退出登录</a<br />  
      16.         <br /> 当前在线人数:<span style="color:red;"<%=UserList.getUserCount()%>人</span>  
      17.         <br />  
      18.         <br> 在线用户名单 : <br /> <select multiple="multiple" name="list"  
      19.             style="200px;height:250px">  
      20.             <%  
      21.                 for (int i = 0; i onlineUsers.size(); i++) {  
      22.                     out.write("<option>" + onlineUsers.get(i) + "</option>");  
      23.                 }  
      24.             %>  
      25.         </select>  
      26.     </center>  
      27. </body>  
  • 相关阅读:
    ASSIC码对照表
    IIS注册 net环境
    Remoting1
    WinCE API
    【可下载】C#中关于zip压缩解压帮助类的封装
    【原创,提供下载】winfrom 打印表格,字符串的封装
    一个可编辑div中粘贴内容时过滤掉粘贴内容的一些特殊的样式或者标签
    限制一个文本框只能输入数字以及限制最大只能输入的数字
    文本框中有默认的文字,写获取焦点和失去焦点的文字显示与消失的效果
    鼠标滑过图片变大,移开还原大小的动画效果
  • 原文地址:https://www.cnblogs.com/feiyudemeng/p/8472951.html
Copyright © 2011-2022 走看看