java web用servlet監(jiān)聽器實(shí)現(xiàn)顯示在線人數(shù)
本文實(shí)例為大家分享了java web用servlet監(jiān)聽器實(shí)現(xiàn)顯示在線人數(shù),供大家參考,具體內(nèi)容如下
1.創(chuàng)建一個(gè)監(jiān)聽器
package com.listener;import javax.servlet.ServletContext;import javax.servlet.http.HttpSessionAttributeListener;import javax.servlet.http.HttpSessionBindingEvent;//使用監(jiān)聽器實(shí)現(xiàn)顯示在線人數(shù)public class MyServletSessionListener implements HttpSessionAttributeListener { @Override public void attributeAdded(HttpSessionBindingEvent event) { // TODO 自動(dòng)生成的方法存根 ServletContext cx = event.getSession().getServletContext();//根據(jù)session對(duì)象獲取當(dāng)前容器的ServletContext對(duì)象 Object objectlogincount = cx.getAttribute('logincount');//獲取容器里面名字為logincount的對(duì)象 String name = event.getName(); if('is'.equals(name)){//如果session增加的屬性名字為is,表示成功登陸一個(gè)用戶 //System.out.println('登陸的用戶名是:'+event.getValue()); if(objectlogincount==null){//如果logincount為空,表示是第一個(gè)登陸 cx.setAttribute('logincount', 1); }else{//表示已經(jīng)有人登陸了 int a = Integer.parseInt(objectlogincount.toString());//轉(zhuǎn)換已經(jīng)登陸的人數(shù) a++; cx.setAttribute('logincount', a); } } System.out.println('當(dāng)前登陸的人數(shù)為:'+cx.getAttribute('logincount')); } @Override public void attributeRemoved(HttpSessionBindingEvent event) { // TODO 自動(dòng)生成的方法存根 } @Override public void attributeReplaced(HttpSessionBindingEvent event) { // TODO 自動(dòng)生成的方法存根 } }
2.在web.xml中配置監(jiān)聽器
<listener> <listener-class>com.listener.MyServletSessionListener</listener-class></listener>
3.用LoginServ(servlet)進(jìn)行測(cè)試
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 自動(dòng)生成的方法存根 String name = req.getParameter('user'); String pwd = req.getParameter('pwd'); if(true){//假設(shè)用get方式提交,所有用戶名密碼都是正確的 HttpSession session = req.getSession(); session.setAttribute('is', name);//setAttribute() 方法添加指定的屬性,并為其賦指定的值。如果這個(gè)指定的屬性已存在,則僅設(shè)置/更改值。 } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO 自動(dòng)生成的方法存根 doGet(req, resp); }}
運(yùn)行截圖:
在瀏覽器上輸入地址:
在myeclipse控制臺(tái)會(huì)輸出:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. JSP的Cookie在登錄中的使用2. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實(shí)現(xiàn)代碼3. HTML5 Canvas繪制圖形從入門到精通4. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁(yè)的方法5. 利用CSS3新特性創(chuàng)建透明邊框三角6. ASP基礎(chǔ)知識(shí)VBScript基本元素講解7. 詳解CSS偽元素的妙用單標(biāo)簽之美8. XHTML 1.0:標(biāo)記新的開端9. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究10. XML入門的常見問(wèn)題(四)
