ajax实现简单的多人聊天

该博客介绍了一个基于Ajax实现的多人聊天系统。通过使用Java Web后端,包括Hibernate和Struts2框架,以及XML数据格式,系统能够在不刷新页面的情况下,利用Ajax的异步特性实时获取和更新聊天消息。前端部分展示了两个关键页面,friend.jsp用于展示好友列表,当用户点击好友时,会打开新的聊天窗口(chating.jsp),该窗口每隔5秒通过Ajax请求后台获取新消息,并实时显示在聊天框中。此外,还提供了一个简单的JavaScript文件(my.js)用于Ajax请求和页面交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原理:简单来说就是利用ajax的异步,ajax每隔一段时间会从后台获取数据而不刷新页面。

步骤:1。数据库里建两张表,一张用户表,一张消息表

isGet表示消息是否被读

2.使用java web做后台,主要使用hibernate和struts2框架,xml数据格式。

3.下面给出核心jsp代码:

friend.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'firend.jsp' starting page</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 <script type="text/javascript" src="my.js"></script>
 <script type="text/javascript">
 
 function change1(val,obj){
 
     if(val=='over'){
         obj.style.color='red';
         obj.style.cursor='hand';
     }
     else if(val=='out'){
         obj.style.color='black';
     }
 
 }
 
 function openChatRoom(obj){
     window.open("${pageContext.request.contextPath}/chat/friend_gotochat.action?username="+encodeURI(obj.innerText),"_blank");
 }
 
 </script>

  </head>
 
  <body>
  <h1>欢迎${user.username }</h1>
   <ul>
   <c:forEach items="${list}" var="everyuser">
   <li onmouseover="change1('over',this)" onclick="openChatRoom(this)"
   onmouseout="change1('out',this)">${everyuser.username }</li>
  
   </c:forEach>
   </ul>
  </body>
</html>

以上代码的功能只是实现当用户点击好友列表的某个好友时,浏览器打开一个新的聊天界面

 


chating.jsp:

 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'chating.jsp' starting page</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 <script type="text/javascript" src="my.js"></script>
   <script type="text/javascript">

//打开新窗口的大小
   window.resizeTo(700,400);

//每隔5秒向后台要数据
   window.setInterval("getMessage()",5000);

//向后台要数据的函数
   function getMessage(){
   var myXmlHttpRequest=getXmlHttpObject();
   if(myXmlHttpRequest){
   var url="${pageContext.request.contextPath}/chat/chat_backchat.action";
   var data="getterid="+'${user.id }'+"&senderid="+'${usertochat.id}';
   myXmlHttpRequest.open("post",url,true);
   myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
   myXmlHttpRequest.onreadystatechange=function (){
   if(myXmlHttpRequest.readyState==4){
   if(myXmlHttpRequest.status==200){

//当数据回来后,将数据显示在指定位置
   var meses=myXmlHttpRequest.responseXML;
   var contents=meses.getElementsByTagName("content");
   var sendtimes=meses.getElementsByTagName("sendtime");
   for(var i=0;i<contents.length;i++){
    var str='${usertochat.username }'+":"+contents[i].childNodes[0].nodeValue+"\r\n"+sendtimes[i].childNodes[0].nodeValue
    $('mycons').value+=str+"\r\n";
   }
   }
   }
   }
   myXmlHttpRequest.send(data);
   }
   }
   //发送数据的函数
   function sendmessage(){
   var myXmlHttpRequest=getXmlHttpObject();
   if(myXmlHttpRequest){
   var url="${pageContext.request.contextPath}/chat/chat_gochat.action";
   var data="con="+${'con'}.value+"&getterid="+'${usertochat.id}'+"&senderid="+'${user.id }';
   //window.alert(data);
   myXmlHttpRequest.open("post",url,true);
   myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
   myXmlHttpRequest.onreadystatechange=function (){
   if(myXmlHttpRequest.readyState==4){
   if(myXmlHttpRequest.status==200){
   }
   }
   }
   myXmlHttpRequest.send(data);
   $('mycons').value+='${user.username }'+":"+$('con').value+"\r\n"+new Date().toLocaleString()+"\r\n";
   $('con').value="";
   }
   }
   </script>
  </head>
 
  <body>
    <h1>聊天室,<font color="red">${user.username }</font>正在和<font color="red">${usertochat.username }</font>聊天</h1>
    <textarea cols="70" rows="10" id="mycons"></textarea><br/>
    <input type="text" id="con" style="width:400px"/>
    <input type="button" value="发送消息" onclick="sendmessage()"/>
  </body>
</html>

 

my.js:

 

//创建ajax
   function getXmlHttpObject(){
   var xmlHttpRequest;
   //XmlHttpObject
   if(window.ActiveXObject)
   {
   //window.alert("ie");
   xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
   }
   else{
   //window.alert("ff");
   xmlHttpRequest=new XmlHttpRequest();
   }
   return xmlHttpRequest;
   }
  
    //获取id
   function $(id){
   return document.getElementById(id);
   }
  
   //encode"+","&"(对加号和空格编码)
   function URLencode(sStr)  

 
    return escape(sStr).replace(/\+/g, '%2B').replace(/\"/g,'%22').replace(/\'/g, '%27').replace(/\//g,'%2F'); 
 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值