java web用servlet監(jiān)聽器實現顯示在線人數
更新時間:2020年03月11日 07:20:00 作者:煙花盛典
這篇文章主要為大家詳細介紹了java web用servlet監(jiān)聽器實現顯示在線人數,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了java web用servlet監(jiān)聽器實現顯示在線人數,供大家參考,具體內容如下
1.創(chuàng)建一個監(jiān)聽器
package com.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
//使用監(jiān)聽器實現顯示在線人數
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中配置監(jiān)聽器
<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);
}
}
運行截圖:
在瀏覽器上輸入地址:

在myeclipse控制臺會輸出:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Springboot源碼 AbstractAdvisorAutoProxyCreator解析
這篇文章主要介紹了Springboot源碼 AbstractAdvisorAutoProxyCreator解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-08-08
Spring 中如何根據環(huán)境切換配置 @Profile
這篇文章主要介紹了Spring中如何根據環(huán)境切換配置@Profile的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08

