本文代碼下載地址:http://download.csdn.net/source/798197
一個簡單的聊天室程式,但基本包含了簡單的AJAX的使用方法,可以做為簡單的Demo用來學習。
整個程式包含三個文件,頁面文件chat.html,後臺處理的Servlet文件Chat.java以及簡單的用戶資料的UserSessionListener.java類。其中chat.html用于接受用戶輸入,並將接收資料傳給後臺Servlet處理,UserSessionListener主要用於登入和登出時用戶列表及提示信息的處理。 
chat.html如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=BIG5" />
<title></title>
<script type="text/javascript">...
var HttpRequest;
var url = "Chat";
function getRequest()...{
    if(window.XMLHttpRequest)...{
        return(new XMLHttpRequest());
    }else if(window.ActiveXObject)...{
        try...{
            return(new ActiveXObject("Msxm12.XMLHTTP"));
        }catch(e)...{
            try...{
                return(new ActiveXObject("Microsoft.XMLHTTP"));
            }catch(e)...{}
        }
    }
}
function sendRequest()...{
    if(document.getElementById("txtMessage").value.length<=0)...{
        return false;
    }
    HttpRequest = getRequest();
    
    //HttpRequest.onreadystatechange = getMessage;
    HttpRequest.open("POST", url, true);
    HttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    var msg;
    msg = "Action=AddMessage&Message=" + escape(document.getElementById("txtMessage").value);
    HttpRequest.send(msg);
    document.getElementById("txtMessage").value = "";
    //document.getElementById("txtMessage").focus();
}
function DisplayMessage()...{
    if(HttpRequest.readyState == 4 && HttpRequest.status == 200)...{
        //alert("abd");
        //alert(HttpRequest.responseText);
        var messages;
        //alert(HttpRequest.responseText);
        messages = HttpRequest.responseText.split("!@#");
        //document.writeln(messages[0]);
        //document.writeln(messages[1]);
        document.getElementById("Messages").innerHTML = messages[0];
        document.getElementById("userList").innerHTML = "User List <br>" + messages[1];
        //document.getElementById
    }
}
function logout()...{
    HttpRequest = getRequest();
    HttpRequest.open("POST", url, true);
    HttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    var msg;
    
    msg = "Action=Logout";
    HttpRequest.send(msg);
}
function getMessage()...{
    HttpRequest = getRequest();
    HttpRequest.onreadystatechange = DisplayMessage;
    HttpRequest.open("POST", url, true);
    HttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    var msg;
    msg = "Action=GetMessage";
    HttpRequest.send(msg);
    document.all.txtMessage.focus();
}
function login()...{
    HttpRequest = getRequest();
    var WshNetwork = new ActiveXObject("WScript.Network");
    
    HttpRequest.open("POST", url, true);
    HttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    var msg;
    msg = "Action=Login&UserName=" + WshNetwork.UserName;
    HttpRequest.send(msg);
    
    setInterval('getMessage();', 1000);
}
function chkSubmit(e)...{
    if(window.event)...{
        var keyNumber = e.keyCode;
        if(keyNumber == 13)...{
            sendRequest();
        }
    }
}
</script>
</head>
<body onunload="logout();" onload="login();">
    <form action="#" onsubmit="return false;">
    <table>
        <tr valign="top">
            <td width="400"><div id="Messages" style="font-size:9pt;width:800;height:400"></div></td>
            <td width="100" id="userList"></td>
        </tr>
    </table>
    <input type="text" size="20" id="txtMessage" onkeypress="chkSubmit(event);">
    <button onclick="sendRequest();">Say</button>
    </form>
</body>
</html>
用於處理頁面提交信息的Servlet Chat.java代碼如下:
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import moon.UserSessionListener;
/** *//**
 * Servlet implementation class for Servlet: Chat
 * 
 */
public class Chat extends javax.servlet.http.HttpServlet implements
  javax.servlet.Servlet ...{
 static final long serialVersionUID = 1L;
 private String userName = "";
 /**//*
  * (non-Java-doc)
  * 
  * @see javax.servlet.http.HttpServlet#HttpServlet()
  */
 public Chat() ...{
  super();
 }
 private String getNow()...{
  Date date = new Date();
  SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
  return df.format(date);  
 }
 
 /**//*
  * (non-Java-doc)
  * 
  * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
  *      HttpServletResponse response)
  */
 @SuppressWarnings("unchecked")
 protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException ...{
  String action = request.getParameter("Action");
  if (action == null) ...{
  } else if (action.equals("GetMessage")) ...{
   PrintWriter out = response.getWriter();
   out.print(getMessages() + "!@#" + getOnlineUsers());
  } else if (action.equals("AddMessage")) ...{
   String message = request.getParameter("Message");
   userName = ((UserSessionListener) request.getSession()
     .getAttribute("UserName")).toString();
   addMessage(getNow() + " " + userName + " Says: " + message);
  }else if(action.equals("Logout"))...{
   request.getSession().removeAttribute("UserName");
  }else if(action.equals("Login"))...{
   request.getSession().setAttribute("UserName", new UserSessionListener(request.getParameter("UserName")));
  }
  // TODO Auto-generated method stub
 }
 /**//*
  * (non-Java-doc)
  * 
  * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
  *      HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException ...{
  doGet(request, response);
  // TODO Auto-generated method stub
 }
 @SuppressWarnings("unchecked")
 private String getMessages() ...{
  String result = null;
  ServletContext application = getServletContext();
  LinkedList<String> messages = (LinkedList<String>) application
    .getAttribute("ChatMessage");
  if (messages == null) ...{
   result = "";
  } else ...{
   StringBuilder sb = new StringBuilder("");
   for (String tmp : messages) ...{
    sb.append(tmp);
    sb.append("<br>");
   }
   result = sb.toString();
  }
  return result;
 }
 @SuppressWarnings("unchecked")
 private String getOnlineUsers() ...{
  String result;
  LinkedList<String> onlineUsers = (LinkedList<String>)getServletContext().getAttribute("UserList");
  if (onlineUsers == null) ...{
   result = "";
  } else ...{
   StringBuilder users = new StringBuilder("");
   for (String tmp : onlineUsers) ...{
    users.append(tmp);
    users.append("<br>");
   }
   result = users.toString();
  }
  return result;
 }
 @SuppressWarnings("unchecked")
 private void addMessage(String message) ...{
  ServletContext application = getServletContext();
  synchronized (application) ...{
   LinkedList<String> messages = (LinkedList<String>) application
     .getAttribute("ChatMessage");
   if (messages == null) ...{
    messages = new LinkedList<String>();
   }
   if (messages.size() > 30) ...{
    messages.removeFirst();
   }
   messages.add(message);
   application.setAttribute("ChatMessage", messages);
  }
 }
 public void destroy() ...{
  super.destroy();
 }
}
用于做用戶登陸,登出處理類UserSessionListener代碼如下:
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
public class UserSessionListener implements HttpSessionBindingListener ...{
 private String userName;
 public UserSessionListener(String userName) ...{
  super();
  this.userName = userName;
 }
 
 private String getNow()...{
  Date date = new Date();
  SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
  return df.format(date);  
 }
 @SuppressWarnings("unchecked")
 public void valueBound(HttpSessionBindingEvent arg0) ...{
  // TODO Auto-generated method stub
  arg0.getSession().setMaxInactiveInterval(120);
  ServletContext application = arg0.getSession().getServletContext();
  synchronized (application) ...{
   LinkedList<String> userList = (LinkedList<String>) application
     .getAttribute("UserList");
   if (userList == null) ...{
    userList = new LinkedList<String>();
   }
   userList.add(userName);
   application.setAttribute("UserList", userList);
   LinkedList<String> messages = (LinkedList<String>) application
     .getAttribute("ChatMessage");
   if (messages == null) ...{
    messages = new LinkedList<String>();
   }
   messages.add(getNow() + " " +  userName + " Login...");
   application.setAttribute("ChatMessage", messages);
  }
 }
 @SuppressWarnings("unchecked")
 public void valueUnbound(HttpSessionBindingEvent arg0) ...{
  // TODO Auto-generated method stub
  ServletContext application = arg0.getSession().getServletContext();
  synchronized (application) ...{
   LinkedList<String> userList = (LinkedList<String>) application
     .getAttribute("UserList");
   userList.remove(userName);
   application.setAttribute("UserList", userList);
   LinkedList<String> messages = (LinkedList<String>) application
     .getAttribute("ChatMessage");
   if (messages == null) ...{
    messages = new LinkedList<String>();
   }
   messages.add(getNow() + " " + userName + " Logout...");
   application.setAttribute("ChatMessage", messages);
  }
 }
 /** *//**
  * @return the userName
  */
 public String getUserName() ...{
  return userName;
 }
 /** *//**
  * @param userName
  *            the userName to set
  */
 public void setUserName(String userName) ...{
  this.userName = userName;
 }
 public String toString() ...{
  return this.userName;
 }
}
其中UserSessionListener類實現了HttpSessionBingdingListener接口,以便于在用戶登入和登出時實現用戶列表的更新。

转载于:https://www.cnblogs.com/moonsnow/archive/2007/09/12/6226920.html

JSP + AJAX 打造簡單聊天室相关推荐

  1. Vue全家桶+Socket.io+Koa2打造一个智能聊天室 接口已开放

    Vue.js+Socket.io+Koa2打造一个智能聊天室 Vue.js全家桶+Socket.io+Express/Koa2 打造的一个智能聊天室. 已经开源啦!为了方便大家学习,智能机器人.IP定 ...

  2. vue php聊天室,Laravel + Swoole 打造IM简易聊天室

    Laravel + Swoole 打造IM简易聊天室 最近在学习Swoole,利用Swoole扩展让PHP生动了不少,本篇就来Swoole开发一款简易的IM聊天室 应用场景:实现简单的即时消息聊天室. ...

  3. 教你从零开始用WebSocket打造一个IM聊天室

    之前我们在 IM即时聊天室(一):WebSocket 和 IM即时聊天室(二): Socket.io + Node.js 两篇文章中介绍了搭建一个IM的所需的技术栈和通信原理.那在这篇文章里我们就来详 ...

  4. 如何打造一个语音聊天室

    语音聊天室这个名词可能有点陌生,实际上相关的产品还是很多的,例如游戏里的开黑语音.在线课堂等.语音聊天室可以认为视频直播的前身,很多音视频平台的架构是从语音聊天室演进为视频直播室的.本文主要介绍语音聊 ...

  5. Web jsp开发学习——网上直播聊天室的简单开发

    整个界面为chat.jsp: 如果用户没有登录,就不能进行聊天. 为将发言的句子传到页面上,要设置一个<iframe></iframe>虚拟框架,将allmessage.jsp ...

  6. 基于jquery的ajax聊天室系统,基于jQuery的Ajax聊天室应用毕业设计(含外文翻译)...

    基于jQuery的Ajax聊天室应用毕业设计(含外文翻译) 毕业设计(论文) I 基于基于 jQuery 的的 Ajax 聊天室应用聊天室应用 摘摘 要要 随着网络的逐渐普及,以及网络技术的不断发展, ...

  7. YShout一款PHP+TXT+Ajax嵌入式在线聊天室源码

    简介: YShout是一款PHP+TXT+AJAX开发嵌入式在线聊天室源码,UTF-8编码. 可以非常方便的嵌入到的你的网站中,无需数据库,采用TXT存储数据,小巧灵活,移植方便.采用AJAX技术,增 ...

  8. 简易聊天室的设计 --- JSP

    目录 1.数据库设计 这里用MySQL数据库,借助phpstudy可快速安装 列名 类型 长度 备注 id smallint 10 主键 username varchar 10 用户登录名 passw ...

  9. AJAX聊天室无刷新技术方案

    聊天室在网上很常见,它给人们提供了在线聊天的机会.聊天室在功能上类似论坛,但是论坛上的信息可以保存较长的时间,而聊天室主要用于在线聊天,所以对存储信息方面的要求不高,另外还要经常删除一些信息,避免数据 ...

最新文章

  1. hibnate 创建表的时候type=innodb报错
  2. CLAMAV 杀毒软件安装及使用配置
  3. 2.5 使用scriptfiles
  4. LintCode 1652. 区间异或 II
  5. Mybatis源码阅读(三):结果集映射3.3 —— 主键生成策略
  6. 如何把安静的程序员逼成话唠
  7. python-描述符的分类
  8. 芒果超媒2021年净利润21亿元 芒果TV会员数达5040万
  9. finallshell使用_FinalShell使用---Xshell的良心国产软件
  10. html div 边框只显示右侧,CSS-只显示角边框
  11. My97DatePicker JS时间控件 当前日期前后不能选
  12. java中怎么创建单列模式,java中的3种方式创建的单例模式
  13. error: warning: Stopped in a context claiming to capture an Objective-C object pointer,
  14. AutoML 前瞻与实践 ---- AutoML 简介
  15. 【前端基础】12.CSS 基础知识学习——基本语法结构
  16. 记一道MISC图片题(拖延癌晚期)
  17. 华为鸿蒙系统超级终端,华为发布鸿蒙OS Connect 打造鸿蒙硬件“超级终端”概念...
  18. 常用知识图谱数据集FB15K, YAGO, WN18
  19. “移”步到位:一站式移动应用研发体系
  20. 16QAM调制解调仿真(matlab,详细介绍仿真方案的设计、结果及结论、完整代码及注释)

热门文章

  1. python | 删除两个指定字符串之间的内容
  2. mysql 核心目录
  3. MySQL逻辑运算符的使用
  4. MySQL 的发展历史和版本分支:
  5. 简单了解各种序列化技术-XML序列化框架介绍
  6. 初步认识Volatile-从硬件层面了解可见性的本质
  7. 创建订单 - 创建订单后前端的业务处理讲解
  8. 基于注解的方式配置bean
  9. Junit_测试概述
  10. 使用fastDFS客户端改造文件上传