怎么在java中使用servlet监听器显示在线人数-创新互联
这期内容当中小编将会给大家带来有关怎么在java中使用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);
}
}上述就是小编为大家分享的怎么在java中使用servlet监听器显示在线人数了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注创新互联网站建设公司行业资讯频道。
另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
网站题目:怎么在java中使用servlet监听器显示在线人数-创新互联
本文路径:http://www.jxjierui.cn/article/dhehge.html


咨询
建站咨询
