一、监听器

监听器是一个专门用于对其他对象身上发生的事件或状态改变进行监听和相应处理的对象,当被监视的对象发生情况时,立即采取相应的行动。监听器其实就是一个实现特定接口的普通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基础学习笔记二十二)的更多相关文章

  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. 体感设备:因特尔 Intel RealSense R200,乐视LeTV Pro Xtion和Orb奥比中光bec Astra比较

    最近调试三个个厂家的体感设备,第一个是Intel的RealSense R200(参数规格:分辨率:1080p,深度有效距离:0.51-4,USB3.0),第二个是乐视LeTV Pro Xtion(参数 ...

  2. hdu1015 Safecracker (暴力枚举)

    http://acm.hdu.edu.cn/showproblem.php?pid=1015 Safecracker Time Limit: 2000/1000 MS (Java/Others)    ...

  3. 浅析Windows系统调用——2种切换到内核模式的方法

    http://shayi1983.blog.51cto.com/4681835/1710861/

  4. 预装Windows 8系统机型如何进行一键恢复

    http://support1.lenovo.com.cn/lenovo/wsi/htmls/detail_20131119141246845.html

  5. axure8.1可用授权码

    Licensee: University of Science and Technology of China (CLASSROOM)Key: DTXRAnPn1P65Rt0xB4eTQ+4bF5IU ...

  6. MVC扩展ActionInvoker,自定义ActionInvoker,根据请求数据返回不同视图

    ActionInvoker的作用是:根据请求数据(HttpPost,HttpGet等)和action名称,来激发响应的action,再由action渲染视图.本文通过自定义ActionInvoker, ...

  7. Log4net 配置输出文本, 按年月日分文件夹 z

    在项目中新建 “log4net.config” 文件 <?xml version="1.0" encoding="utf-8" ?> <con ...

  8. UITableView的headerView展开缩放动画

    UITableView的headerView展开缩放动画 效果 源码 https://github.com/YouXianMing/Animations // // HeaderViewTapAnim ...

  9. CAShapeLayer的path动画

    CAShapeLayer的path动画 效果 源码 https://github.com/YouXianMing/Animations // // CAShapeLayerPathController ...

  10. utf-8-validation

    https://leetcode.com/problems/utf-8-validation/ public class Solution { public boolean validUtf8(int ...