网络聊天室

    xiaoxiao2021-03-25  197

    今天的网络聊天室是简单的利用几个域对象对多个页面进行消息传递的一个事情,思路很简单,代码也很简单。

    那么现在就进行我们的代码编写吧!

    1、首先我们需要有个登录页面

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

    Insert title here

    <% String alert=request.getParameter("alert"); if(alert!=null){ out.println(""); } %>

    账号: 密码:   

     

    2、然后跳转到登录的业务逻辑对数据库进行判断

     

     

    <%@page import="com.student.entity.Logins"%> <%@page import="com.student.dao.LoginDao"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> Insert title here<% //使用

    标签中的post时会出现中文乱码的情况,这句代码是防止乱码的发生 request.setCharacterEncoding("UTF-8"); //通过request属性获得账号和密码 String uname=request.getParameter("uname"); String upwd=request.getParameter("upwd"); //调用方法对登录进行判断 LoginDao ld=new LoginDao(); boolean b=ld.getLogin(new Logins(uname,upwd)); if(b){ //如果返回为ture,则用session保存用户名,转发到聊天室页面 session.setAttribute("uname", uname); request.getRequestDispatcher("chatroom.jsp").forward(request, response); }else{ //如果错误,则返回到登录页面,我设置了返回一个名为alert的值,让登录页面进行消息弹出框提示 request.getRequestDispatcher("login.jsp?alert=a").forward(request, response); } %>

    3、登录的业务逻辑判断完之后,我们就到了聊天室页面

     

     

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> Insert title here<% request.setCharacterEncoding("UTF-8"); //用来暂时记录聊天 String all=""; Object o=application.getAttribute("all"); if(o!=null){ all=o.toString(); } %> 你好:<%=session.getAttribute("uname") %>

    <%=all%>

     

    4、在聊天室互发消息的时候,需要到聊天的业务逻辑进行判断

     

     

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> Insert title here<% request.setCharacterEncoding("UTF-8"); //获取用户名 String uname=session.getAttribute("uname").toString(); //获取application的值 String all=""; Object o=application.getAttribute("all"); if(o!=null){ all=o.toString(); } //获取要发送的内容 String sendInfo=request.getParameter("sendInfo").toString(); //指定特定的用户不同的颜色 if(uname.equals("admin")){ all=all+" "+" "+uname+":"+sendInfo+""; }else{ all=all+" "+" "+uname+":"+sendInfo+""; } //存起来 application.setAttribute("all", all); //重定向 response.sendRedirect("chatroom.jsp"); %> 就这四步就可以把一个简单的聊天室给做好,是不是很简单呢~

     

     

     

     

     

     

    转载请注明原文地址: https://ju.6miu.com/read-97002.html

    最新回复(0)