这期内容当中小编将会给大家带来有关怎么在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中配置监听器
<listener>
<listener-class>com.listener.MyServletSessionListener</listener-class>
</listener>
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监听器显示在线人数了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。