美文网首页
Servlet之网上实时聊天室

Servlet之网上实时聊天室

作者: 红Archer | 来源:发表于2018-01-04 23:47 被阅读0次

Web聊天室(基于Servlet)
主要实现思路:使用Servlet作用域的概念,通过使用session、ServletContext进行传值。
注意事项:这里使用了request.setCharacterEncoding("UTF-8");的转码方式,所以在提交表单时需要将方法设置为post方法

1、用户登陆
1)显示登陆界面
2)接收登陆的用户名(用户名需要传递给后面的代码)
ServletContext(Set<String>)其中为何使用Set来存用户列表而不是List,因为Set不可允许重复,可以少一层判断
Session保存自己用户名
用于和集合中比对,找出自己的,改颜色
3)转向到聊天室界面
2、显示聊天室界面
1)界面:frameset+frame
2)实时显示在线用户
显示
1)获取在线用户(ServletContext)
从Session中获取当前用户,控制自己显示的颜色
2)生成html元素显示
实时

3)实时显示聊天信息
4)发送聊天信息
接收:将信息保存在上下文
List<String[]>

登陆界面代码(LoginServlet)
···

public class LoginServlet extends HttpServlet {

@Override
protected void service(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    res.setContentType("text/html;charset=UTF-8");
    PrintWriter out = res.getWriter();
    boolean msg=false;
    
    //获取用户名
    String userName = req.getParameter("userName"); 
    //判断是否有值
    ServletContext ctx = this.getServletContext();
    Set<String> userNameSet = (Set<String>)ctx.getAttribute("USER_SET");
    if(userName != null&&!"".equals(userName))
    {
        if(!(userNameSet != null&&userNameSet.contains(userName)))
        {
            //若没有登陆过,则写入Session、写入上下文
            req.getSession().setAttribute("LOGIN_USER", userName);
            if(userNameSet == null)
            {
                //若用户集合不存在则创建
                userNameSet = new HashSet<String>();
                ctx.setAttribute("USER_SET", userNameSet);
            }
            userNameSet.add(userName);
            req.getRequestDispatcher("mainServlet").forward(req, res);
            return;
        }else{
            msg = true;
        }
    }
    out.println("<form action='loginServlet' method='post'>");
    out.println("请输入用户名:");
    out.println("<input type ='text' name='userName'/>");
    out.println("<input type = 'submit' value='登陆'/>");
    out.println("</form>");
    if(msg)
    {
        out.println("<script type='text/javascript'>");
        out.println("alert('"+userName+"已经登陆,请输入另一个用户名');");
        out.println("</script>");
        System.out.println("已经登陆");
    }
}

}

···

主显示区域代码


public class MainServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        out.println("<html>");
        out.println("<frameset rows='70%,*'>");
        out.println("<frameset cols='70%,*'>");
        out.println("<frame src='viewMsgServlet' name='viewMsgServlet'/>");
        out.println("<frame src='userMsgServlet'/>");
        out.println("</frameset>");
        out.println("<frame src='sendMsgServlet'/>");
        out.println("</frameset>");
        out.println("</html>");
    }

}

显示当前登陆用户代码


public class UserMsgServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        resp.addHeader("Refresh", "2");//两秒后发一下当前的请求
        PrintWriter out = resp.getWriter();
        
        //获取上下文中的用户集合
        //获取当前用户名
        Set<String> userSet = (Set<String>)req.getSession().getServletContext().getAttribute("USER_SET");
        String userName = (String)req.getSession().getAttribute("LOGIN_USER");
        out.println("<HTML>");
        out.println("<body>");
        
        if(userSet != null)
        {
            for(String user:userSet)
            {
                if(userName != null&& userName.equals(user))
                {
                    out.println("<font color='red'>"+user+"</font><br>");
                }else
                    out.println(user+"<br>");
            }
        }
        
        out.println("</body>");
        out.println("</HTML>");
    }

}

发送消息界面代码

public class SendMsgServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        //获取消息
        String msg = req.getParameter("msg");
        System.out.println(msg);
        if(msg != null&&!"".equals(msg))
        {
            HttpSession session = req.getSession();
            //获取当前用户名
            String userName = (String)session.getAttribute("LOGIN_USER");
            ServletContext stx = session.getServletContext();
            String[] msgs = {userName,msg};
            List<String[]> msgList = (List<String[]>)stx.getAttribute("MSGS_LIST");
            if(msgList==null)
            {
                msgList = new ArrayList<String[]>();
                stx.setAttribute("MSGS_LIST", msgList);
            }
            msgList.add(msgs);
        }
        
        
        out.println("<html>");
        out.println("<body>");
        
        out.println("<form action='sendMsgServlet' method='post'>");
        out.println("请输入信息:");
        out.println("<input type='text' name='msg'/>");
        out.println("<input type='submit' value='提交'/>");
        out.println("</form>");
        
        out.println("</body>");
        out.println("</html>");
        
    }

}

显示消息区域代码

public class ViewMsgServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        resp.setHeader("Refresh", "2");
        PrintWriter out = resp.getWriter();
        //获取得到的信息
        HttpSession session = req.getSession();
        ServletContext ctx = session.getServletContext();
        List<String[]> msgsList = (List<String[]>)ctx.getAttribute("MSGS_LIST");
        //获取当前用户名
        String userName = (String)session.getAttribute("LOGIN_USER");

        out.println("<HTML>");
        out.println("<body>");
        if(msgsList!=null)
        {
            for(String[] msgs:msgsList)
            {
                out.println(msgs[0]+"说:"+msgs[1]);
                out.println("<br>");
            }
        }
        out.println("</body>");
        out.println("</HTML>");
    }

}

相关文章

网友评论

      本文标题:Servlet之网上实时聊天室

      本文链接:https://www.haomeiwen.com/subject/vqklnxtx.html