统计在线和登陆人数,管理这些用户

来源:互联网 发布:淘宝代码需要修改热点 编辑:程序博客网 时间:2024/04/29 11:22

思想:

1:统计在线人数。

              只是访问了这个网页的人员。

       2:统计登录人数。

              是指输出的正确的用户名和密码以后用户的数量。

       3:获取每一个登录人的IP,什么时间登录的,获取最近活动时间。

                             登录人的姓名。

4:做为管理员,应该可以将某些用户踢出。

              如何才可以将别人踢出去?

              获取别人的session,执行那个session.invalidate();

项目结构:

第一步:先开发统计在线人数

      
        session的创建就是一个在线人数+1。让所有人都可以看到。把在线人数放到ServletContext中。

 

思想:实现HttpSessionListener,在sessionCreated的方法 中+1,sessionDestroyed的方法中-1.

publicclass OnlineListener implements HttpSessionListener {

 

   //当有人访问时就会有一个session被创建,就会别session监听器监听到

    publicvoidsessionCreated(HttpSessionEvent se) {

         //app中获取原访问量然后+1

        ServletContextapp = se.getSession().getServletContext();

        AtomicIntegeronline = (AtomicInteger) app.getAttribute("online");

        if(online==null){

            online=new AtomicInteger(1);

        }else{

            online.addAndGet(1);

        }

        //放回到app

        app.setAttribute("online",online);

    }

   //当有人下线时

    publicvoidsessionDestroyed(HttpSessionEvent se) {

        //app中获取访问量

        ServletContextapp = se.getSession().getServletContext();

        AtomicIntegeronline = (AtomicInteger) app.getAttribute("online");

        online.addAndGet(-1);

        //放回到app

        app.setAttribute("online",online);       

    }

   

}

第二步:什么是登录人数(用session的属性监听)

    是指输入了用户名和密码的用户。

    登录以后:将用户以xxxkey(如以userkey)放到session的属性中去。

    就可以监听登录人数。
   

应该是实现一个HttpSessionAttributeListner监听器。

监听属性的变化:

1:开发登录页面 login.jsp

<body>

    在线人数:${online.get() }<br/>

    登录人数:<ahref="<c:urlvalue='/jsps/show.jsp'/>">${logined.get() }</a>

    <br/>

    <c:choose>

        <c:whentest="${emptysessionScope.user}">

            <form action="<c:urlvalue='LoginServlet'/>"method="post">

                name:<inputtype="text"name="name"><br/> 

                <input type="submit"value=" 登录">

            </form>

        </c:when>

        <c:otherwise>

              欢迎你:${user }<br/>

              <a href="<c:urlvalue='LoginServlet'/>">退出</a>

        </c:otherwise>

    </c:choose>

 

</body>


2:开发登录的LoginServlet

publicclassLoginServlet extends HttpServlet {

    privatestatic finallong serialVersionUID= 1L;

    /**

     * 操作用户退出

     */

    publicvoiddoGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException {

       //删除保存在session的数据

        request.getSession().removeAttribute("user");

        //重定向到login.jsp

        response.sendRedirect(request.getContextPath()+"/login.jsp");

    }

   /**

     * 操作用户登录

     */

    publicvoiddoPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException {

        request.setCharacterEncoding("UTF-8");

        //获取用户名

        String name = request.getParameter("name");

        if(name!=null&&!name.trim().equals("")){

        System.err.println("登录成功。。");

        //把此用户放到session

        request.getSession().setAttribute("user", name.trim());

        //获取ip

        Stringip = request.getRemoteAddr();

        request.getSession().setAttribute("ip", ip);

        request.getSession().setAttribute("loginTime",System.currentTimeMillis());

       

        }else{

        System.err.println("登录不成功。");

        }

        //重定向到登陆页面

       response.sendRedirect(request.getContextPath()+"/login.jsp");

    }

 

}

3:开发属性监听器LoginListener,用户计算登录人数


publicclass LoginListener implements HttpSessionAttributeListener {

    /**

     * 执行了session.setAttribute("user",)

     */

    publicvoidattributeAdded(HttpSessionBindingEvent se) {

        Stringkey = se.getName();

        if (key.equals("user")) {

            ServletContextapp = se.getSession().getServletContext();

            AtomicIntegerlogined = (AtomicInteger) app.getAttribute("logined");

            if (logined ==null) {

                logined= newAtomicInteger(1);

            }else{

                logined.addAndGet(1);

            }

            // 放回到app

            app.setAttribute("logined",logined);

            // 以下是维护登录人的session

            // session放到map中,将map放到app

            Map<String,HttpSession> loginedMap =(Map<String, HttpSession>) app

                   .getAttribute("loginedMap");

            if (loginedMap ==null) {

                loginedMap= newHashMap<String, HttpSession>();

                // 放到app

                app.setAttribute("loginedMap",loginedMap);

            }

            // session放到map

            HttpSessionsession = se.getSession();

            loginedMap.put(session.getId(),session);

        }

 

    }

 

    /**

     * 执行了session.removeAttribute("user",)

     */

    publicvoidattributeRemoved(HttpSessionBindingEvent se) {

        Stringkey = se.getName();

        if (key.equals("user")) {

            // 获取app,读取登陆人数

            ServletContextapp = se.getSession().getServletContext();

            AtomicIntegerlogined = (AtomicInteger) app.getAttribute("logined");

            logined.addAndGet(-1);

            // 把登陆人数放回到app

            app.setAttribute("logined",logined);

 

            // 有人退出就从这个map中删除这个key

            Map<String,HttpSession> loginedMap =(Map<String, HttpSession>) app

                   .getAttribute("loginedMap");

            loginedMap.remove(se.getSession().getId());

        }

 

    }

 

    publicvoidattributeReplaced(HttpSessionBindingEvent se) {

    }

 

}

 

第三步:维护所有的登录人的sesson,修改LoginListener 

思想:修改监听器,将所有session以id为key以session为对象保存map

    再将map放到application:


 // 以下是维护登录人的session

            // session放到map中,将map放到app

            Map<String,HttpSession> loginedMap = (Map<String, HttpSession>) app

                   .getAttribute("loginedMap");

            if (loginedMap == null) {

                loginedMap= newHashMap<String, HttpSession>();

                // 放到app

                app.setAttribute("loginedMap",loginedMap);

            }

            // session放到map

            HttpSessionsession = se.getSession();

            loginedMap.put(session.getId(),session);



第四步:开发一个显示列表的页面show.jsp


<body>

    <c:iftest="${emptysessionScope.user}">

        <c:redirecturl="/login.jsp"></c:redirect>

    </c:if>

    <p>以下是登录人信息</p>

    <tableborder="1"width="800">

        <tr>

            <td>序号</td>

            <td>IP</td>

            <td>Name</td>

            <td>登录时间</td>

            <td>最后访问时间</td>

            <td>踢出</td>

        </tr>

        <c:forEachitems="${loginedMap}"var="entry"varStatus="idx">

            <tr>

                <td>${idx.count }</td>

                <td>${entry.value.getAttribute("ip") }</td>

                <td>${entry.value.getAttribute("user") }</td>

                <td>

                   <%

                   Entry<String,HttpSession> e =(Entry<String,HttpSession>)pageContext.getAttribute("entry");

                    HttpSession hs =e.getValue();

                    SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                    String time = sdf.format(new Date(Long.parseLong(""+hs.getAttribute("loginTime"))));

                   %>

                   <%=time %>

                </td>

                <td>

                       <%

                         Entry<String,HttpSession> e2 =(Entry<String,HttpSession>)pageContext.getAttribute("entry");

                          HttpSession hs2 =e2.getValue();

                         SimpleDateFormat sdf2 =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                          String time2 =sdf.format(newDate(Long.parseLong(""+hs2.getLastAccessedTime())));

                       %>

                       <%=time2 %>

                </td>

               

                <td><ahref="<c:urlvalue='/KickServlet?sid=${entry.key}'/>">踢人</a></td>

            </tr>

        </c:forEach>

    </table>

</body>

第五步:将某人踢出KickServlet 

publicclass KickServlet extends HttpServlet {

    privatestatic finallong serialVersionUID= 1L;

 

    publicvoiddoGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException,IOException {

         //获取准备踢出的人sid

        Stringsid = request.getParameter("sid");

        //根据sidloginedMap获取这个id对应的session

        Map<String,HttpSession>loginedMap =(Map<String, HttpSession>) getServletContext().getAttribute("loginedMap");

        //获取这个session

        HttpSession session =loginedMap.get(sid);

        if(session!=null){

            session.invalidate();

        }

        //重定向到显示页面

        response.sendRedirect(request.getContextPath()+"/jsps/show.jsp");

    }

 

}



原创粉丝点击