事件监听之统计登录用户人数(含用户名)案例

Posted gdwkong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了事件监听之统计登录用户人数(含用户名)案例相关的知识,希望对你有一定的参考价值。

(一)创建一个User类,用于封装一个用户信息,该类实现了HttpSessionBindingListener接口中的valueBound()方法
和valueUnbound()方法


1
package entity; 2 3 import javax.servlet.annotation.WebListener; 4 import javax.servlet.http.*; 5 6 @WebListener() 7 public class User implements HttpSessionBindingListener { 8 9 private String username; 10 private String password; 11 private String id; 12 13 public String getUsername() { 14 return username; 15 } 16 17 public void setUsername(String username) { 18 this.username = username; 19 } 20 21 public String getPassword() { 22 return password; 23 } 24 25 public void setPassword(String password) { 26 this.password = password; 27 } 28 29 public String getId() { 30 return id; 31 } 32 33 public void setId(String id) { 34 this.id = id; 35 } 36 37 @Override 38 public void valueBound(HttpSessionBindingEvent event) { 39 //将user存入列表 40 OnlineUser.getInstance().addUser(this); 41 } 42 43 @Override 44 public void valueUnbound(HttpSessionBindingEvent event) { 45 OnlineUser.getInstance().removeUser(this); 46 } 47 }

 (二)创建OnlineUser类,用于存储和获取在用户的列表,而这个列表对于所有的页面来说应该是同一个,故为单例模式。

 1 package entity;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 
 6 public class OnlineUser {
 7     private OnlineUser() {}
 8     private static OnlineUser instance = new OnlineUser ();
 9     public static OnlineUser getInstance() {
10         return instance;
11     }
12     private Map userMap = new HashMap();
13     //将用户添加到列表中
14     public void addUser(User user){
15         userMap.put (user.getId (),user.getUsername ());
16     }
17     //将用户移除列表
18     public void removeUser(User user){
19         userMap.remove (user.getId ());
20     }
21     //返回用户列表
22     public Map getOnlineUser() {
23         return userMap;
24     }
25 }

(三)编写一个login.jsp页面,该页面输入用户的登录名和密码,完成用户登录功能 

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <head>
 4     <title>Title</title>
 5 </head>
 6 <body>
 7     <center>
 8         <h3>用户登录</h3>
 9     </center>
10 <form action="${pageContext.request.contextPath}/LoginServlet" method="post">
11     <table border="1" width="550px" cellpadding="0" cellspacing="0" align="center">
12         <tr>
13             <td height="35" align="center">用户名</td>
14             <td>
15                 &nbsp;&nbsp;&nbsp;
16                 <input type="text" name="username"/>
17             </td>
18         </tr>
19         <tr>
20             <td height="35" align="center">&nbsp;</td>
21             <td>
22                 &nbsp;&nbsp;&nbsp;
23                 <input type="password" name="password"/>
24             </td>
25         </tr>
26         <tr>
27             <td height="35" colspan="2" align="center">
28                 <input type="submit" value="登录"/>
29                 &nbsp;&nbsp;&nbsp;&nbsp;
30                 <input type="reset" name="重置"/>
31             </td>
32         </tr>
33     </table>
34 </form>
35 </body>
36 </html>

 (四)创建LoginServlet类,用于处理用户登录请求,如果用户登录成功就将该用户的信息封装到User中存入Session对象。

 1 package servlet;
 2 
 3 import entity.OnlineUser;
 4 import entity.User;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.annotation.WebServlet;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 import java.io.IOException;
12 import java.util.Map;
13 import java.util.UUID;
14 
15 @WebServlet(name = "LoginServlet",urlPatterns = "/LoginServlet")
16 public class LoginServlet extends HttpServlet {
17     protected void doPost(HttpServletRequest request, HttpServletResponse response)
18             throws ServletException, IOException {
19         request.setCharacterEncoding ("utf-8");
20         response.setContentType ("text/html;charset=utf-8");
21         String username = request.getParameter ("username");
22         String password = request.getParameter ("password");
23         if (username !=null && !username.trim ().equals ("")){
24             //登录成功
25             User user = new User ();
26             user.setId (UUID.randomUUID ().toString ());
27             user.setUsername (username);
28             user.setPassword (password);
29             request.getSession ().setAttribute ("user",user);
30             Map users = OnlineUser.getInstance ().getOnlineUser ();
31             request.setAttribute ("users",users);
32             request.getRequestDispatcher ("/showuser.jsp").forward (request,response);
33         } else {
34             request.setAttribute ("errorMsg","用户名或密码错误");
35             request.getRequestDispatcher ("/login.jsp").forward (request,response);
36         }
37     }
38 
39     protected void doGet(HttpServletRequest request, HttpServletResponse response)
40             throws ServletException, IOException {
41         this.doPost (request,response);
42     }
43 }

 (五)编写一个showuser.jsp,该页面用于显示所有用户登录信息以及当前的登录的用户。

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 3 <html>
 4 <head>
 5     <title>Title</title>
 6 </head>
 7 <body>
 8   <c:choose>
 9   <c:when test="${sessionScope.user==null}">
10   <a href="${pageContext.request.contextPath}/login.jsp">登录</a>
11       <br/>
12   </c:when>
13       <c:otherwise>
14               欢迎你,${sessionScope.user.username}
15           <a href="${pageContext.request.contextPath}/LogoutServlet">退出</a>
16       </c:otherwise>
17   </c:choose>
18 <hr/>
19 在线用户列表
20 <br/>
21 <c:forEach var="user" items="${requestScope.users}">
22     ${user.value}
23 </c:forEach>
24 </body>
25 </html>

 (六)编写一个LogoutServlet类,用于注销用户登录信息,用户注销后跳转到showuser.jsp页面

 1 package servlet;
 2 
 3 import entity.OnlineUser;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.annotation.WebServlet;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 import java.io.IOException;
11 import java.util.Map;
12 
13 @WebServlet(name = "LogoutServlet",urlPatterns = "/LogoutServlet")
14 public class LogoutServlet extends HttpServlet {
15     protected void doPost(HttpServletRequest request, HttpServletResponse response)
16             throws ServletException, IOException {
17         request.setCharacterEncoding ("utf-8");
18         response.setContentType ("text/html;charset=utf-8");
19         request.getSession ().removeAttribute ("user");
20         Map users = OnlineUser.getInstance ().getOnlineUser ();
21         request.setAttribute ("users",users);
22         request.getRequestDispatcher ("/showuser.jsp").forward (request,response);
23     }
24     protected void doGet(HttpServletRequest request, HttpServletResponse response)
25             throws ServletException, IOException {
26         this.doPost (request,response);
27     }
28 }

(七)使用不同浏览访问,呈现效果如下:

 

以上是关于事件监听之统计登录用户人数(含用户名)案例的主要内容,如果未能解决你的问题,请参考以下文章

监听器实现案例----自定义session扫描器和统计在线用户人数及用户信息

Servlet事件监听器来写一个统计网站当前人数-完整代码

Redis集群环境下的键值空间监听事件实现方案

监听器应用统计网站人数自定义session扫描器踢人小案例

Java统计用户在线人数

servlet监听器统计在线人数