监听器(web基础学习笔记二十二)
一、监听器
监听器是一个专门用于对其他对象身上发生的事件或状态改变进行监听和相应处理的对象,当被监视的对象发生情况时,立即采取相应的行动。监听器其实就是一个实现特定接口的普通java程序,这个程序专门用于监听另一个java对象的方法调用或属性改变,当被监听对象发生上述事件后,监听器某个方法立即被执行。
二、监听器统计在线人数--HttpSessionListener实现
- package com.pb.news.listenter;
- public class OnlineCounter {
- public static long ONLINE_USER_COUNT=0;
- public static long getonline(){
- return ONLINE_USER_COUNT;
- }
- public static void raise() {
- ONLINE_USER_COUNT++;
- }
- public static void reduce() {
- ONLINE_USER_COUNT--;
- }
- }
- package com.pb.news.listenter;
- import javax.servlet.http.HttpSessionEvent;
- import javax.servlet.http.HttpSessionListener;
- /**
- * Application Lifecycle Listener implementation class OnlineCounterListener
- *
- */
- public class OnlineCounterListener implements HttpSessionListener {
- /**
- * @see HttpSessionListener#sessionCreated(HttpSessionEvent)
- */
- public void sessionCreated(HttpSessionEvent arg0) {
- // TODO Auto-generated method stub
- //session创建里用户加1
- OnlineCounter.raise();
- }
- /**
- * @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
- */
- public void sessionDestroyed(HttpSessionEvent arg0) {
- //session销毁里里用户减1
- OnlineCounter.reduce();
- }
- }
只需要在页面中写入
- 在线人数:<%=OnlineCounter.getonline() %>
三、监听器统计在线人数--HttpSessionBindingListener实现绑定用户登录查询在线人数
创建静态变量类
- package com.pb.news.constants;
- public class Constants {
- //统计在线人线人数静态常量
- public static int ONLINE_USER_COUNT=0;
- }
创建用户类来实现-接口-HttpSessionBindingListener
- package com.pb.news.listenter;
- import javax.servlet.http.HttpSessionBindingEvent;
- import javax.servlet.http.HttpSessionBindingListener;
- import com.pb.news.constants.Constants;
- /**
- * Application Lifecycle Listener implementation class UserLoginCount
- *
- */
- public class UserLoginCount implements HttpSessionBindingListener {
- private int id; //用户id;
- private String username; //用户姓名
- private String password; //用户密码
- private String email; //用户邮箱
- private int usertype; //用户类型
- //getter和setter方法
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public int getUsertype() {
- return usertype;
- }
- public void setUsertype(int usertype) {
- this.usertype = usertype;
- }
- /**
- * Default constructor.
- */
- public UserLoginCount() {
- // TODO Auto-generated constructor stub
- }
- /**
- * @see HttpSessionBindingListener#valueBound(HttpSessionBindingEvent)
- */
- public void valueBound(HttpSessionBindingEvent arg0) {
- Constants.ONLINE_USER_COUNT++;
- }
- /**
- * @see HttpSessionBindingListener#valueUnbound(HttpSessionBindingEvent)
- */
- public void valueUnbound(HttpSessionBindingEvent arg0) {
- Constants.ONLINE_USER_COUNT--;
- }
- }
创建登录servlet类
- package com.pb.news.web.servlet;
- import java.io.IOException;
- import javax.servlet.RequestDispatcher;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- import com.pb.news.dao.impl.UsersDaoImpl;
- import com.pb.news.entity.Users;
- import com.pb.news.listenter.UserLoginCount;
- import com.pb.news.service.impl.UsersServiceImpl;
- /**
- * Servlet implementation class UserLoginServlet
- */
- public class UserLoginServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- /**
- * @see HttpServlet#HttpServlet()
- */
- public UserLoginServlet() {
- super();
- // TODO Auto-generated constructor stub
- }
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- // TODO Auto-generated method stub
- }
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- //request.setCharacterEncoding("utf-8");
- String username=request.getParameter("username");
- String password=request.getParameter("password");
- UsersServiceImpl usersService=new UsersServiceImpl();
- UsersDaoImpl usersDao=new UsersDaoImpl();
- usersService.setUsersDao(usersDao);
- boolean flag=usersService.login(username, password);
- if(flag==true){
- //request.getSession().setAttribute("user", username);
- //创建HttpSessio对象
- /*Users users=new Users();
- users.setUsername(username);
- users.setPassword(password);*/
- UserLoginCount users= new UserLoginCount();
- users.setUsername(username);
- users.setPassword(password);
- HttpSession s=request.getSession();
- s.setAttribute("user", users);
- //s.setAttribute("pwd", password);
- //request.getRequestDispatcher("jsp/index.jsp").forward(request, response);
- response.sendRedirect("jsp/index.jsp");
- }else{
- request.setAttribute("msg", "用户名或者密码不正确");
- RequestDispatcher rd=request.getRequestDispatcher("jsp/userLogin.jsp");
- rd.forward(request, response);
- //request.getRequestDispatcher("jsp/userLogin.jsp").forward(request, response);
- //response.sendRedirect("jsp/userLogin.jsp");
- }
- }
- }
在要显示的页面显示
- 已登录用户:<%=com.pb.news.constants.Constants.ONLINE_USER_COUNT %>
相比较,第一种更简洁,这里可能还有理简单的输出,暂时没发现
四、监听器统计在线人数--HttpSessionListener实现
- package com.pb.news.web.servlet;
- import javax.servlet.http.HttpSessionEvent;
- import javax.servlet.http.HttpSessionListener;
- public class UserCountListener implements HttpSessionListener {
- private int count = 0;
- public void sessionCreated(HttpSessionEvent se) {
- // TODO Auto-generated method stub
- //人数加1
- count++;
- setContext(se);
- }
- public void sessionDestroyed(HttpSessionEvent se) {
- // TODO Auto-generated method stub
- //人数减1
- count--;
- setContext(se);
- }
- private void setContext(HttpSessionEvent se){
- se.getSession().getServletContext().setAttribute("userCount",new Integer(count));
- }
- }
- 创建UserCountListener监听器,注意web.xml中要有:
- <listener>
- <listener-class>com.pb.news.web.servlet.UserCountListener</listener-class>
- </listener>
- 创建监听器后,可以在需要显示人数的页面加入下面的语句:
- Object userCount=session.getServletContext().getAttribute("userCount");
- out.print(userCount.toString());
五、不需要登录统计在线人数
- package com.pb.listenter;
- import javax.servlet.ServletContext;
- import javax.servlet.annotation.WebListener;
- import javax.servlet.http.HttpSessionEvent;
- import javax.servlet.http.HttpSessionListener;
- /**
- * Application Lifecycle Listener implementation class CountListenter
- *
- */
- @WebListener
- public class CountListenter implements HttpSessionListener {
- //private int count=0;
- /**
- * Default constructor.
- */
- public CountListenter() {
- // TODO Auto-generated constructor stub
- }
- /**
- * 创建seesion+1
- */
- public void sessionCreated(HttpSessionEvent se) {
- // TODO Auto-generated method stub
- ServletContext context=se.getSession().getServletContext();
- Integer count=(Integer) context.getAttribute("count");
- if(count==null){
- //count=new Integer(1);
- context.setAttribute("count", 1);
- }else{
- count++;
- context.setAttribute("count", count);
- }
- }
- /**
- * 销毁session时次数-1
- */
- public void sessionDestroyed(HttpSessionEvent se) {
- // TODO Auto-generated method stub
- ServletContext context=se.getSession().getServletContext();
- Integer count=(Integer) context.getAttribute("count");
- count--;
- context.setAttribute("count", count);
- }
- }
在需要显示的页面输入以下代码显示
- <%
- ServletContext context=session.getServletContext();
- Integer count=(Integer)context.getAttribute("count");
- %>
- <%=count%>
监听器(web基础学习笔记二十二)的更多相关文章
- Python基础学习笔记(十二)文件I/O
参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-files-io.html ▶ 键盘输入 注意raw_input函 ...
- python基础学习笔记(十二)
模块 前面有简单介绍如何使用import从外部模块获取函数并且为自己的程序所用: >>> import math >>> math.sin(0) #sin为正弦函数 ...
- VSTO 学习笔记(十二)自定义公式与Ribbon
原文:VSTO 学习笔记(十二)自定义公式与Ribbon 这几天工作中在开发一个Excel插件,包含自定义公式,根据条件从数据库中查询结果.这次我们来做一个简单的测试,达到类似的目的. 即在Excel ...
- 汇编入门学习笔记 (十二)—— int指令、port
疯狂的暑假学习之 汇编入门学习笔记 (十二)-- int指令.port 參考: <汇编语言> 王爽 第13.14章 一.int指令 1. int指令引发的中断 int n指令,相当于引 ...
- Binder学习笔记(十二)—— binder_transaction(...)都干了什么?
binder_open(...)都干了什么? 在回答binder_transaction(...)之前,还有一些基础设施要去探究,比如binder_open(...),binder_mmap(...) ...
- java之jvm学习笔记六-十二(实践写自己的安全管理器)(jar包的代码认证和签名) (实践对jar包的代码签名) (策略文件)(策略和保护域) (访问控制器) (访问控制器的栈校验机制) (jvm基本结构)
java之jvm学习笔记六(实践写自己的安全管理器) 安全管理器SecurityManager里设计的内容实在是非常的庞大,它的核心方法就是checkPerssiom这个方法里又调用 AccessCo ...
- MySQL数据库学习笔记(十二)----开源工具DbUtils的使用(数据库的增删改查)
[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...
- salesforce 零基础学习(五十二)Trigger使用篇(二)
第十七篇的Trigger用法为通过Handler方式实现Trigger的封装,此种好处是一个Handler对应一个sObject,使本该在Trigger中写的代码分到Handler中,代码更加清晰. ...
- Android学习笔记(十二)——实战:制作一个聊天界面
//此系列博文是<第一行Android代码>的学习笔记,如有错漏,欢迎指正! 运用简单的布局知识,我们可以来尝试制作一个聊天界面. 一.制作 Nine-Patch 图片 : Nine-Pa ...
随机推荐
- CF 277.5 A.SwapSort 水题
//STL教你做人系列 #include<stdio.h> #include<iostream> #include<math.h> #include<algo ...
- jmeter3.3—插件管理器的安装
一.介绍JMeter Plugins 一直以来, JMeter Plugins 为我们提供了很多高价值的JMeter插件,比如: 用于服务器性能监视的 PerfMon Metrics Collecto ...
- AbstractAction
package cn.tz.action.abs; import java.io.File; import java.io.IOException; import java.text.SimpleDa ...
- Android字体简述
Android是一个典型的Linux内核的操作系统.在Android系统中,主要有DroidSans和DroidSerif两大字体阵营,从名字就可以看出来,前者是无衬线字体,后者是衬线字体.具体来说, ...
- 详解Google Chrome浏览器(操作篇)(上)
开篇概述 在上篇博客中详解Google Chrome浏览器(理论篇)一文中,主要讲解了Chrome 搜索引擎使用.Chrome安装和基本操作.Chrome 基本架构.多线程等原理性问题,这篇将重点讲解 ...
- 你得学会并且学得会的Socket编程基础知识(续)——Silverlight客户端
本文将在这个案例的基础上,加入一个特殊场景,利用Silverlight来实现客户端.有的朋友可能会说,其实是一样的吧.请不要急于下结论,有用过Silverlight的朋友都有这种体会,很多在标准.NE ...
- 高手写的“iOS 的多核编程和内存管理”
原文地址:http://anxonli.iteye.com/blog/1097777 多核运算 在iOS中concurrency编程的框架就是GCD(Grand Central Dispatch), ...
- python接口自动化26-参数关联和JSESSIONID(上个接口返回数据作为下个接口请求参数)
前言 参数关联是接口测试和性能测试最为重要的一个步骤,很多接口的请求参数是动态的,并且需要从上一个接口的返回值里面取出来,一般只能用一次就失效了. 最常见的案例就是网站的登录案例,很多网站的登录并不仅 ...
- Android Gradle Plugin指南(四)——測试
原文地址:http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Testing 5.Testing(測试) 构建一个測试 ...
- 基于非比較的排序:计数排序(countSort),桶排序(bucketSort),基数排序(radixSort)
计数排序 条件:要排序的数组的元素必须是在一定范围的,比方是1~100.在排序之前我们必须知道数组元素的范围. 思路:顾名思义:就是用一个数组来计数的. 步骤: 1.用一个数组来计数count[ ], ...