关闭

网站如何实现在线人数、管理员踢人等功能?

84人阅读 评论(0) 收藏 举报
分类:

网站概述

1.网站仅两个页面,主页index.jsp和显示在线用户的show.jsp。游客(未登录用户)只能范问主页,登录的过的仅部分用户(名字为Jack)的用户为管理员可以踢人.
这里写图片描述
主页代码

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>在线用户人数</title>
  </head>

  <body>
        <h2>在线用户~</h2>
        <hr/>
        <c:if test="${empty user}">
            <form action="<c:url value='/LoginServlet'/>" method="post">
                Name:<input type="text" name="name"> <br/>
                Pwd:<input type="password" name="pwd"><br/>
                <input type="submit" value="提交"><br/>
            </form>
        </c:if>
        <br/>
        <a href="<c:url value='/ShowServlet'/>">在线用户查看</a>
  </body>
</html>

这里写图片描述
show.jsp代码

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <style type="text/css">
        table{
            border: solid red 1px;
            border-collapse: collapse;
            width:75%;
        }
        td{
            border: solid red 1px;
            padding:3px;
        }
        .header{
            background: gray;
        }
      </style>

    <title>在线用户管理</title>
  </head>

  <body>
            <h1>在线用户管理</h1>
            <hr>
            <table>
                <tr class="header">
                    <td>姓名</td>
                    <td>上线时间</td>
                    <td>最近访问时间</td>
                    <td>IP地址</td>
                    <td>操作</td>
                </tr>
                <c:forEach items="${datas}" var="map">
                    <tr>
                        <td> 
                            <c:if test="${empty map.user}" var="boo">游客</c:if>
                          <c:if test="${!boo}"> ${map.user.name}</c:if>
                        </td>
                        <td>
                            <fmt:formatDate value="${map.createTime}" pattern="yyyy-MM-dd HH-mm-SS"/>
                        </td>
                        <td>
                            <fmt:formatDate value="${map.lastAccessedTime}" pattern="yyyy-MM-dd HH-mm-SS"/>
                        </td>
                        <td>${map.ip}</td>
                        <td> 
                             <c:if test="${!boo && sessionScope.user.admin }">
                                <c:if test="${map.user.id !=sessionScope.user.id }">
                                    <a href="<c:url value='/OutServlet'/>?id=${map.user.id }">踢人</a> 
                                </c:if>
                             </c:if>
                        </td>
                    </tr>
                </c:forEach>
            </table>
  </body>
</html>

配置文件Web.xml代码

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>
  <listener>
    <listener-class>cn.hncu.listener.onLinesListener</listener-class>
  </listener>
  <filter>
    <filter-name>LoginFilter</filter-name>
    <filter-class>cn.hncu.filters.LoginFilter</filter-class>
  </filter>
  <filter>
    <filter-name>PreFilter</filter-name>
    <filter-class>cn.hncu.filters.PreFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name> PreFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <url-pattern>/jsps/*</url-pattern>
    <servlet-name>ShowServlet</servlet-name>
    <dispatcher>REQUEST</dispatcher>
  </filter-mapping>
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>cn.hncu.servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>ShowServlet</servlet-name>
    <servlet-class>cn.hncu.servlet.ShowServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>OutServlet</servlet-name>
    <servlet-class>cn.hncu.servlet.OutServlet</servlet-class>
  </servlet>



  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>ShowServlet</servlet-name>
    <url-pattern>/ShowServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>OutServlet</servlet-name>
    <url-pattern>/OutServlet</url-pattern>
  </servlet-mapping>



  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

网址代码分层

这里写图片描述

domain层– 值对象,用于封装数据的User

public class User {
    private String id;
    private String name;
    private String pwd;
    private boolean admin;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    public boolean isAdmin() {
        return admin;
    }
    public void setAdmin(boolean admin) {
        this.admin = admin;
    }
    @Override
    public String toString() {
        return "User " + id + ", name=" + name;
    }

}

filter,过滤器— 两个过滤器
LoginFilter 登录拦截,没登录的用户通通拦到主页

package cn.hncu.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginFilter implements Filter{

    @Override
    public void init(FilterConfig paramFilterConfig) throws ServletException {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest paramServletRequest,
            ServletResponse paramServletResponse, FilterChain paramFilterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) paramServletRequest;
        HttpServletResponse respone = (HttpServletResponse) paramServletResponse;
        if(request.getSession().getAttribute("user")!=null){// 游客只能访问主页
            paramFilterChain.doFilter(paramServletRequest, paramServletResponse);
        }else{
//          respone.sendRedirect(request.getContextPath()+"/index.jsp");
            request.getRequestDispatcher("/index.jsp").forward(paramServletRequest, paramServletResponse);
        }

    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

}

PreFilter 通用设置–设置编码 显示格式等

package cn.hncu.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class PreFilter implements Filter{

    @Override
    public void init(FilterConfig paramFilterConfig) throws ServletException {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest request,
            ServletResponse response, FilterChain paramFilterChain)
            throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        paramFilterChain.doFilter(request, response);
        // 设置好每次请求的的IP 
        String ip = request.getRemoteAddr();
        ((HttpServletRequest)request).getSession().setAttribute("ip", ip);
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }


}

listener 监听器— 用来判断是否有新的用户进来和旧的用户离开

package cn.hncu.listener;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class onLinesListener implements HttpSessionListener{
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("一个用户上线--");
        // 每当一个Session创建-- 说明一个用户上线
         Map<String, HttpSession> onlines =(Map<String, HttpSession>) se.getSession().getServletContext().getAttribute("onLines");

        if(onlines == null){
            //※※java.util.Collections类中可以帮我们创建出各种同步集合
            onlines = Collections.synchronizedMap( new HashMap<String, HttpSession>());
            se.getSession().getServletContext().setAttribute("onLines", onlines);
        }
        onlines.put(se.getSession().getId(), se.getSession());

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("一个用户下线--");
        // 每当一个Session消亡-- 说明一个用户下线
         Map<String, HttpSession> onlines =(Map<String, HttpSession>) se.getSession().getServletContext().getAttribute("onLines");
        if(onlines.containsKey(se.getSession().getId())){
            onlines.remove(se.getSession().getId());
        }

    }

}

Servlet层—登录、显示、已经踢人 三个功能的实现

package cn.hncu.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hncu.domain.User;

public class LoginServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }   

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        User user = new User();
        if(name!=null && pwd!=null && name.trim().length()>1){
            user.setName(name);
            user.setPwd(pwd);
            user.setAdmin(false);
            user.setId(request.getSession().getId() );
            if(name.equalsIgnoreCase("jack")){
                user.setAdmin(true);
            }
            request.getSession().setAttribute("user", user);
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        }else{
            response.getWriter().println("登陆失败,请输入正确格式的账号密码~");
        }
    }

}
package cn.hncu.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ShowServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Map<String,HttpSession> onlines = (Map<String, HttpSession>) request.getServletContext().getAttribute("onLines");
        List<Map<String, Object>> datas = new ArrayList<Map<String,Object>>();

        Iterator<Map.Entry<String, HttpSession>> it = onlines.entrySet().iterator();
        while(it.hasNext()){
            HashMap<String, Object> map = new HashMap<String, Object>();
            Entry<String, HttpSession> en = it.next();
            // 两个需要我们设置到HttpSession容器的信息
            // user---为空的时候表示未登录的游客
            map.put("user", en.getValue().getAttribute("user"));
            map.put("ip",en.getValue().getAttribute("ip") );

            // HttpSession里面的自带的信息
            map.put("id", en.getValue().getId());
            map.put("lastAccessedTime", new Date(en.getValue().getLastAccessedTime()));
            map.put("createTime", new Date(en.getValue().getCreationTime()));

            datas.add(map);
        }
        request.setAttribute("datas",datas);
        request.getRequestDispatcher("/jsps/show.jsp").forward(request, response);
    }

}
package cn.hncu.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.hncu.domain.User;

public class OutServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id= request.getParameter("id");
         Map<String, HttpSession> onlines =(Map<String, HttpSession>) request.getServletContext().getAttribute("onLines");
         Iterator<Map.Entry<String, HttpSession>> it = onlines.entrySet().iterator();
            while(it.hasNext()){
                Entry<String, HttpSession> en = it.next();
                if(en.getKey().equals(id)){
                    en.getValue().setAttribute("user", null);
                }
            }
        request.getRequestDispatcher("/ShowServlet").forward(request, response);
    }

}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:30729次
    • 积分:2884
    • 等级:
    • 排名:第12550名
    • 原创:268篇
    • 转载:2篇
    • 译文:0篇
    • 评论:8条