新聞中心
這篇文章將為大家詳細講解有關利用servlet如何實現(xiàn)一個監(jiān)聽在線人數(shù)功能,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
公司主營業(yè)務:做網(wǎng)站、成都網(wǎng)站建設、移動網(wǎng)站開發(fā)等業(yè)務。幫助企業(yè)客戶真正實現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競爭能力。創(chuàng)新互聯(lián)公司是一支青春激揚、勤奮敬業(yè)、活力青春激揚、勤奮敬業(yè)、活力澎湃、和諧高效的團隊。公司秉承以“開放、自由、嚴謹、自律”為核心的企業(yè)文化,感謝他們對我們的高要求,感謝他們從不同領域給我們帶來的挑戰(zhàn),讓我們激情的團隊有機會用頭腦與智慧不斷的給客戶帶來驚喜。創(chuàng)新互聯(lián)公司推出雁江免費做網(wǎng)站回饋大家。
具體內(nèi)容如下
ServletContext事件監(jiān)聽器---->針對applicationScope
ServletContextListener(*)
對整個Web應用的裝載和卸載進行監(jiān)聽。
ServletContextAttributeListener
對ServletContext中的信息存放、刪除和替換進行監(jiān)聽。
ServletContext就是Servlet上下文監(jiān)聽,在web中表示的是對啟動服務和銷毀服務進行監(jiān)聽,需要實現(xiàn)的接口:
ServletContextListener接口,實現(xiàn)的就是對上下午進行監(jiān)聽:
void contextInitialized(ServletContextEvent sce):啟動上下文時的監(jiān)聽
void contextDestroyed(ServletContextEvent sce):銷毀上下文時進行的監(jiān)聽
除了對上下文的啟動和銷毀進行監(jiān)聽的之外,還可以對上下文的屬性進行監(jiān)聽:ServletContextAttributeListener接口。
void attributeAdded(ServletContextAttributeEvent event):設置上下文屬性監(jiān)聽
void attributeRemoved(ServletContextAttributeEvent event):移除上下文屬性的監(jiān)聽
void attributeReplaced(ServletContextAttributeEvent event):修改上下文屬性的監(jiān)聽
ServletContextAttributeEvent:事件,可以通過事件取得屬性的內(nèi)容和名稱。
·取得屬性名稱:public java.lang.String getName()
·取得屬性的值:public java.lang.Object getValue()
效果如下圖:
當?shù)卿浺粋€賬號時
打開另一個瀏覽器,再登錄一個賬號
如上圖,我們可以看到,程序已經(jīng)完成了統(tǒng)計在線人數(shù)和顯示人員列表的功能,那么他的實現(xiàn)流程是什么呢?
我們可以通過ServletContextListener完成在線人數(shù)的統(tǒng)計和顯示在線人數(shù)列表,首先listener和filter一樣要在web.xml中進行描述。
代碼如下:
net.jvsun.ListenerTest
為了測試這個程序,我們也必須完成用戶登錄功能。
數(shù)據(jù)庫連接幫助類:
public class JDBCHelper { public static final String DRIVER = "oracle.jdbc.driver.OracleDriver"; public static final String URL = "jdbc:oracle:thin:@localhost:1521:xxx"; public static final String DBNAME = "scott"; public static final String PASSWORD = "xxx"; public static Connection getConn() throws Exception{ Class.forName(DRIVER); Connection conn = DriverManager.getConnection(URL, DBNAME, PASSWORD); return conn; } }
用戶實體類:
public class UserPOJO implements Serializable{ private static final long serialVersionUID = 7554548269035753256L; private int id; private String username; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public UserPOJO(int id, String username, String password) { super(); this.id = id; this.username = username; this.password = password; } public UserPOJO(String username, String password) { this.username = username; this.password = password; } public UserPOJO() { super(); // TODO Auto-generated constructor stub } }
數(shù)據(jù)庫處理類:
public class UserDAO { public UserPOJO login(String username, String password) { UserPOJO user=null; Connection conn = null; PreparedStatement pstate = null; ResultSet res = null; try { conn=JDBCHelper.getConn(); String sql="select id,username from userinfo where username=? and password=?"; pstate = conn.prepareStatement(sql); pstate.setString(1, username); pstate.setString(2, password); res = pstate.executeQuery(); while(res.next()){ user=new UserPOJO(res.getInt(1),username,null); } } catch (Exception e) { e.printStackTrace(); }finally{ try { res.close(); pstate.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return user; } }
servlet類:
public class UserServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = request.getContextPath(); response.setContentType("text/html; charset=utf-8"); request.setCharacterEncoding("utf-8"); String username = request.getParameter("username"); String password = request.getParameter("password"); ServletContext application = this.getServletContext();//取得application對象 Listlist = (List ) application.getAttribute("allUser"); if(list.indexOf(username) == -1){ UserPOJO pojo = new UserDAO().login(username, password); if(null != pojo){ HttpSession session = request.getSession(true);//取得session對象 session.setAttribute("userName", username); } } response.sendRedirect(path+"/index.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
監(jiān)聽類:
public class ListenerTest implements ServletContextListener,HttpSessionAttributeListener,HttpSessionListener{ ServletContext application = null; public void contextDestroyed(ServletContextEvent event) { System.out.println("服務器關閉"); } public void contextInitialized(ServletContextEvent event) { Listlist = new ArrayList (); //用來保存所有已登錄的用戶 application = event.getServletContext(); //取得application對象 application.setAttribute("allUser", list); //將集合設置到application范圍屬性中去 } public void attributeAdded(HttpSessionBindingEvent se) { List list = (List )application.getAttribute("allUser"); //假設:用戶登陸成功之后,只將戶名設置到session中 String userName = (String)se.getValue(); //取得用戶名 if(list.indexOf(userName) == -1){ //表示此用戶之前沒有登陸 list.add(userName); application.setAttribute("allUser", list); } } public void attributeRemoved(HttpSessionBindingEvent se) { List list = (List )application.getAttribute("allUser"); list.remove((String)se.getValue()); application.setAttribute("allUser", list); } public void attributeReplaced(HttpSessionBindingEvent se) { } public void sessionCreated(HttpSessionEvent event) { } public void sessionDestroyed(HttpSessionEvent event) { } }
登錄頁面
<%@page contentType="text/html; charset=utf-8"%> <%@page import="java.util.*" %> <% String path = request.getContextPath(); %>
顯示在線人數(shù)和在線人員的列表界面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>" rel="external nofollow" rel="external nofollow" >
-
<%
System.out.println(application.getAttribute("allUser"));
if(null != application.getAttribute("allUser")){
List
在線人數(shù):<%=list.size() %>
<% for(String s:list){ %> 姓名:<%=s %>---->此時在線<% } } %>
注銷
注銷界面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>logout <% session.removeAttribute("username"); session.invalidate(); response.sendRedirect("login.jsp"); %>
關于利用servlet如何實現(xiàn)一個監(jiān)聽在線人數(shù)功能就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
當前名稱:利用servlet如何實現(xiàn)一個監(jiān)聽在線人數(shù)功能
路徑分享:http://www.dlmjj.cn/article/jgheii.html