一、监听器

监听器是一个专门用于对其他对象身上发生的事件或状态改变进行监听和相应处理的对象,当被监视的对象发生情况时,立即采取相应的行动。监听器其实就是一个实现特定接口的普通java程序,这个程序专门用于监听另一个java对象的方法调用或属性改变,当被监听对象发生上述事件后,监听器某个方法立即被执行。

二、监听器统计在线人数--HttpSessionListener实现

  1. package com.pb.news.listenter;
  2.  
  3. public class OnlineCounter {
  4. public static long ONLINE_USER_COUNT=0;
  5. public static long getonline(){
  6. return ONLINE_USER_COUNT;
  7. }
  8.  
  9. public static void raise() {
  10. ONLINE_USER_COUNT++;
  11. }
  12.  
  13. public static void reduce() {
  14. ONLINE_USER_COUNT--;
  15. }
  16. }
  1. package com.pb.news.listenter;
  2.  
  3. import javax.servlet.http.HttpSessionEvent;
  4. import javax.servlet.http.HttpSessionListener;
  5.  
  6. /**
  7. * Application Lifecycle Listener implementation class OnlineCounterListener
  8. *
  9. */
  10. public class OnlineCounterListener implements HttpSessionListener {
  11.  
  12. /**
  13. * @see HttpSessionListener#sessionCreated(HttpSessionEvent)
  14. */
  15. public void sessionCreated(HttpSessionEvent arg0) {
  16. // TODO Auto-generated method stub
  17. //session创建里用户加1
  18. OnlineCounter.raise();
  19. }
  20.  
  21. /**
  22. * @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
  23. */
  24. public void sessionDestroyed(HttpSessionEvent arg0) {
  25. //session销毁里里用户减1
  26. OnlineCounter.reduce();
  27. }
  28.  
  29. }

只需要在页面中写入

  1. 在线人数:<%=OnlineCounter.getonline() %>

三、监听器统计在线人数--HttpSessionBindingListener实现绑定用户登录查询在线人数

创建静态变量类

  1. package com.pb.news.constants;
  2.  
  3. public class Constants {
  4. //统计在线人线人数静态常量
  5. public static int ONLINE_USER_COUNT=0;
  6. }

创建用户类来实现-接口-HttpSessionBindingListener

  1. package com.pb.news.listenter;
  2.  
  3. import javax.servlet.http.HttpSessionBindingEvent;
  4. import javax.servlet.http.HttpSessionBindingListener;
  5.  
  6. import com.pb.news.constants.Constants;
  7.  
  8. /**
  9. * Application Lifecycle Listener implementation class UserLoginCount
  10. *
  11. */
  12. public class UserLoginCount implements HttpSessionBindingListener {
  13. private int id; //用户id;
  14. private String username; //用户姓名
  15. private String password; //用户密码
  16. private String email; //用户邮箱
  17. private int usertype; //用户类型
  18.  
  19. //getter和setter方法
  20. public int getId() {
  21. return id;
  22. }
  23. public void setId(int id) {
  24. this.id = id;
  25. }
  26. public String getUsername() {
  27. return username;
  28. }
  29. public void setUsername(String username) {
  30. this.username = username;
  31. }
  32. public String getPassword() {
  33. return password;
  34. }
  35. public void setPassword(String password) {
  36. this.password = password;
  37. }
  38. public String getEmail() {
  39. return email;
  40. }
  41. public void setEmail(String email) {
  42. this.email = email;
  43. }
  44. public int getUsertype() {
  45. return usertype;
  46. }
  47. public void setUsertype(int usertype) {
  48. this.usertype = usertype;
  49. }
  50.  
  51. /**
  52. * Default constructor.
  53. */
  54. public UserLoginCount() {
  55. // TODO Auto-generated constructor stub
  56. }
  57.  
  58. /**
  59. * @see HttpSessionBindingListener#valueBound(HttpSessionBindingEvent)
  60. */
  61. public void valueBound(HttpSessionBindingEvent arg0) {
  62. Constants.ONLINE_USER_COUNT++;
  63. }
  64.  
  65. /**
  66. * @see HttpSessionBindingListener#valueUnbound(HttpSessionBindingEvent)
  67. */
  68. public void valueUnbound(HttpSessionBindingEvent arg0) {
  69. Constants.ONLINE_USER_COUNT--;
  70. }
  71.  
  72. }

创建登录servlet类

  1. package com.pb.news.web.servlet;
  2.  
  3. import java.io.IOException;
  4.  
  5. import javax.servlet.RequestDispatcher;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. import javax.servlet.http.HttpSession;
  11.  
  12. import com.pb.news.dao.impl.UsersDaoImpl;
  13. import com.pb.news.entity.Users;
  14. import com.pb.news.listenter.UserLoginCount;
  15. import com.pb.news.service.impl.UsersServiceImpl;
  16.  
  17. /**
  18. * Servlet implementation class UserLoginServlet
  19. */
  20. public class UserLoginServlet extends HttpServlet {
  21. private static final long serialVersionUID = 1L;
  22.  
  23. /**
  24. * @see HttpServlet#HttpServlet()
  25. */
  26. public UserLoginServlet() {
  27. super();
  28. // TODO Auto-generated constructor stub
  29. }
  30.  
  31. /**
  32. * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  33. */
  34. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  35. // TODO Auto-generated method stub
  36. }
  37.  
  38. /**
  39. * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  40. */
  41. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  42. //request.setCharacterEncoding("utf-8");
  43. String username=request.getParameter("username");
  44. String password=request.getParameter("password");
  45. UsersServiceImpl usersService=new UsersServiceImpl();
  46. UsersDaoImpl usersDao=new UsersDaoImpl();
  47. usersService.setUsersDao(usersDao);
  48. boolean flag=usersService.login(username, password);
  49. if(flag==true){
  50. //request.getSession().setAttribute("user", username);
  51. //创建HttpSessio对象
  52. /*Users users=new Users();
  53. users.setUsername(username);
  54. users.setPassword(password);*/
  55. UserLoginCount users= new UserLoginCount();
  56. users.setUsername(username);
  57. users.setPassword(password);
  58. HttpSession s=request.getSession();
  59. s.setAttribute("user", users);
  60. //s.setAttribute("pwd", password);
  61. //request.getRequestDispatcher("jsp/index.jsp").forward(request, response);
  62. response.sendRedirect("jsp/index.jsp");
  63.  
  64. }else{
  65. request.setAttribute("msg", "用户名或者密码不正确");
  66. RequestDispatcher rd=request.getRequestDispatcher("jsp/userLogin.jsp");
  67. rd.forward(request, response);
  68. //request.getRequestDispatcher("jsp/userLogin.jsp").forward(request, response);
  69. //response.sendRedirect("jsp/userLogin.jsp");
  70. }
  71.  
  72. }
  73.  
  74. }

在要显示的页面显示

  1. 已登录用户:<%=com.pb.news.constants.Constants.ONLINE_USER_COUNT %>

相比较,第一种更简洁,这里可能还有理简单的输出,暂时没发现

四、监听器统计在线人数--HttpSessionListener实现

  1. package com.pb.news.web.servlet;
  2.  
  3. import javax.servlet.http.HttpSessionEvent;
  4. import javax.servlet.http.HttpSessionListener;
  5.  
  6. public class UserCountListener implements HttpSessionListener {
  7. private int count = 0;
  8.  
  9. public void sessionCreated(HttpSessionEvent se) {
  10. // TODO Auto-generated method stub
  11. //人数加1
  12. count++;
  13. setContext(se);
  14.  
  15. }
  16.  
  17. public void sessionDestroyed(HttpSessionEvent se) {
  18. // TODO Auto-generated method stub
  19. //人数减1
  20. count--;
  21. setContext(se);
  22.  
  23. }
  24. private void setContext(HttpSessionEvent se){
  25. se.getSession().getServletContext().setAttribute("userCount",new Integer(count));
  26. }
  27.  
  28. }
  1. 创建UserCountListener监听器,注意web.xml中要有:
  2. <listener>
  3. <listener-class>com.pb.news.web.servlet.UserCountListener</listener-class>
  4. </listener>
  5.  
  6. 创建监听器后,可以在需要显示人数的页面加入下面的语句:
  7. Object userCount=session.getServletContext().getAttribute("userCount");
  8. out.print(userCount.toString());

五、不需要登录统计在线人数

  1. package com.pb.listenter;
  2.  
  3. import javax.servlet.ServletContext;
  4. import javax.servlet.annotation.WebListener;
  5. import javax.servlet.http.HttpSessionEvent;
  6. import javax.servlet.http.HttpSessionListener;
  7.  
  8. /**
  9. * Application Lifecycle Listener implementation class CountListenter
  10. *
  11. */
  12. @WebListener
  13. public class CountListenter implements HttpSessionListener {
  14. //private int count=0;
  15. /**
  16. * Default constructor.
  17. */
  18. public CountListenter() {
  19. // TODO Auto-generated constructor stub
  20. }
  21.  
  22. /**
  23. * 创建seesion+1
  24. */
  25. public void sessionCreated(HttpSessionEvent se) {
  26. // TODO Auto-generated method stub
  27. ServletContext context=se.getSession().getServletContext();
  28. Integer count=(Integer) context.getAttribute("count");
  29. if(count==null){
  30. //count=new Integer(1);
  31. context.setAttribute("count", 1);
  32. }else{
  33. count++;
  34. context.setAttribute("count", count);
  35. }
  36.  
  37. }
  38.  
  39. /**
  40. * 销毁session时次数-1
  41. */
  42. public void sessionDestroyed(HttpSessionEvent se) {
  43. // TODO Auto-generated method stub
  44. ServletContext context=se.getSession().getServletContext();
  45. Integer count=(Integer) context.getAttribute("count");
  46. count--;
  47. context.setAttribute("count", count);
  48.  
  49. }
  50.  
  51. }

在需要显示的页面输入以下代码显示

  1. <%
  2. ServletContext context=session.getServletContext();
  3. Integer count=(Integer)context.getAttribute("count");
  4. %>
  5.   <%=count%>

监听器(web基础学习笔记二十二)的更多相关文章

  1. Python基础学习笔记(十二)文件I/O

    参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-files-io.html ▶ 键盘输入 注意raw_input函 ...

  2. python基础学习笔记(十二)

    模块 前面有简单介绍如何使用import从外部模块获取函数并且为自己的程序所用: >>> import math >>> math.sin(0) #sin为正弦函数 ...

  3. VSTO 学习笔记(十二)自定义公式与Ribbon

    原文:VSTO 学习笔记(十二)自定义公式与Ribbon 这几天工作中在开发一个Excel插件,包含自定义公式,根据条件从数据库中查询结果.这次我们来做一个简单的测试,达到类似的目的. 即在Excel ...

  4. 汇编入门学习笔记 (十二)—— int指令、port

    疯狂的暑假学习之  汇编入门学习笔记 (十二)--  int指令.port 參考: <汇编语言> 王爽 第13.14章 一.int指令 1. int指令引发的中断 int n指令,相当于引 ...

  5. Binder学习笔记(十二)—— binder_transaction(...)都干了什么?

    binder_open(...)都干了什么? 在回答binder_transaction(...)之前,还有一些基础设施要去探究,比如binder_open(...),binder_mmap(...) ...

  6. java之jvm学习笔记六-十二(实践写自己的安全管理器)(jar包的代码认证和签名) (实践对jar包的代码签名) (策略文件)(策略和保护域) (访问控制器) (访问控制器的栈校验机制) (jvm基本结构)

    java之jvm学习笔记六(实践写自己的安全管理器) 安全管理器SecurityManager里设计的内容实在是非常的庞大,它的核心方法就是checkPerssiom这个方法里又调用 AccessCo ...

  7. MySQL数据库学习笔记(十二)----开源工具DbUtils的使用(数据库的增删改查)

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

  8. salesforce 零基础学习(五十二)Trigger使用篇(二)

    第十七篇的Trigger用法为通过Handler方式实现Trigger的封装,此种好处是一个Handler对应一个sObject,使本该在Trigger中写的代码分到Handler中,代码更加清晰. ...

  9. Android学习笔记(十二)——实战:制作一个聊天界面

    //此系列博文是<第一行Android代码>的学习笔记,如有错漏,欢迎指正! 运用简单的布局知识,我们可以来尝试制作一个聊天界面. 一.制作 Nine-Patch 图片 : Nine-Pa ...

随机推荐

  1. CF 277.5 A.SwapSort 水题

    //STL教你做人系列 #include<stdio.h> #include<iostream> #include<math.h> #include<algo ...

  2. jmeter3.3—插件管理器的安装

    一.介绍JMeter Plugins 一直以来, JMeter Plugins 为我们提供了很多高价值的JMeter插件,比如: 用于服务器性能监视的 PerfMon Metrics Collecto ...

  3. AbstractAction

    package cn.tz.action.abs; import java.io.File; import java.io.IOException; import java.text.SimpleDa ...

  4. Android字体简述

    Android是一个典型的Linux内核的操作系统.在Android系统中,主要有DroidSans和DroidSerif两大字体阵营,从名字就可以看出来,前者是无衬线字体,后者是衬线字体.具体来说, ...

  5. 详解Google Chrome浏览器(操作篇)(上)

    开篇概述 在上篇博客中详解Google Chrome浏览器(理论篇)一文中,主要讲解了Chrome 搜索引擎使用.Chrome安装和基本操作.Chrome 基本架构.多线程等原理性问题,这篇将重点讲解 ...

  6. 你得学会并且学得会的Socket编程基础知识(续)——Silverlight客户端

    本文将在这个案例的基础上,加入一个特殊场景,利用Silverlight来实现客户端.有的朋友可能会说,其实是一样的吧.请不要急于下结论,有用过Silverlight的朋友都有这种体会,很多在标准.NE ...

  7. 高手写的“iOS 的多核编程和内存管理”

    原文地址:http://anxonli.iteye.com/blog/1097777 多核运算 在iOS中concurrency编程的框架就是GCD(Grand Central Dispatch), ...

  8. python接口自动化26-参数关联和JSESSIONID(上个接口返回数据作为下个接口请求参数)

    前言 参数关联是接口测试和性能测试最为重要的一个步骤,很多接口的请求参数是动态的,并且需要从上一个接口的返回值里面取出来,一般只能用一次就失效了. 最常见的案例就是网站的登录案例,很多网站的登录并不仅 ...

  9. Android Gradle Plugin指南(四)——測试

    原文地址:http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Testing 5.Testing(測试) 构建一个測试 ...

  10. 基于非比較的排序:计数排序(countSort),桶排序(bucketSort),基数排序(radixSort)

    计数排序 条件:要排序的数组的元素必须是在一定范围的,比方是1~100.在排序之前我们必须知道数组元素的范围. 思路:顾名思义:就是用一个数组来计数的. 步骤: 1.用一个数组来计数count[ ], ...