java web用servlet监听器实现显示在线人数

网友投稿 251 2022-12-12


java web用servlet监听器实现显示在线人数

本文实例为大家分享了java web用servlet监听器实现显示在线人数,供大家参考,具体内容如下

1.创建一个监听器

package com.listener;

import javax.servlet.ServletContext;

import javax.servlet.http.HttpSessionAttributeListener;

import javax.servlet.http.HttpSessionBindingEvent;

//使用监听器实现显示在线人数

public class MyServletSessionListener implements HttpSessionAttributeListener {

@Override

public void attributeAdded(HttpSessionBindingEvent event) {

// TODO 自动生成的方法存根

ServletContext cx = event.getSession().getServletContext();//根据session对象获取当前容器的ServletContext对象

Object objectlogincount = cx.getAttribute("logincount");//获取容器里面名字为logincount的对象

String name = event.getName();

if("is".equals(name)){//如果session增加的属性名字为is,表示成功登陆一个用户

//System.out.println("登陆的用户名是:"+event.getValue());

if(objectlogincount==null){//如果logincount为空,表示是第一个登陆

cx.setAttribute("logincount", 1);

}else{//表示已经有人登陆了

int a = Integer.parseInt(objectlogincount.toString());//转换已经登陆的人数

a++;

cx.setAttribute("logincount", a);

}

}

System.out.println("当前登陆的人数为:"+cx.getAttribute("logincount"));

}

@Override

public void attributeRemoved(HttpSessionBindingEvent event) {

// TODO 自动生成的方法存根

}

@Override

public void attributeReplaced(HttpSessionBindingEvent event) {

// TODO 自动生成的方法存根

}

}

2.在web.xml中配置监听器

com.listener.MyServletSessionListener

3.用LoginServ(servlet)进行测试

package com.serv;

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

@WebServlet(urlPatterns={"/LoginServ"})

public class LoginServ extends HttpServlet {

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

// TODO 自动生成的方法存根

String name = req.getParameter("user");

String pwd = req.getParameter("pwd");

if(true){//假设用get方式提交,所有用户名密码都是正确的

HttpSession session = req.getSession();

session.setAttribute("is", name);//setAttribute() 方法添加指定的属性,并为其赋指定的值。如果这个指定的属性已存在,则仅设置/更改值。

}

}

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

// TODO 自动生成的方法存根

doGet(req, resp);

}

}

运行截图:

在浏览器上输入地址:

在myeclipse控制台会输出:


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:简单了解JAVA public class与class区别
下一篇:Java封装数组之动态数组实现方法详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~