结构:

index.html

<!DOCTYPE html>
<html>
<head>
<title>index.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript">
var xmlHttp; function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
} function firstRead() {
createXMLHttpRequest();
xmlHttp.open("post", "servlet/ChatServlet", true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //post 传参必须有form表单和此句
xmlHttp.onreadystatechange = onReadyState;
xmlHttp.send(null);
window.setTimeout(firstRead, 1000);
} function sendMsg(){
createXMLHttpRequest();
xmlHttp.open("post", "servlet/ChatServlet", true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //post 传参必须有form表单和此句
xmlHttp.onreadystatechange = onReadyState;
var chatMsg = document.getElementById("chatInfo");
xmlHttp.send("chatMsg="+chatMsg.value);
//document.getElementById("showChat").innerText = chatMsg;
document.getElementById("chatInfo").value= "";//清空文本框
} function onReadyState() { //onreadystatechangem 每次状态改变被调用 if (xmlHttp.readyState == 4){//==4 客户端与服务器交互完成,,, ==200是否传输成功.,
if(xmlHttp.status == 200){
//alert("服务器返回: " + xmlHttp.responseText);//responseText 返回服务器数据
document.getElementById("showChat").innerText = xmlHttp.responseText;
}
}
} function getKeyCode(){
if(window.event.keyCode == 13){//回车键
sendMsg();
}
}
</script>
</head> <body onload="firstRead()" onkeydown="getKeyCode()">
<form action="" enctype="application/x-www-form-urlencoded">
This is my HTML page. <br>
<div>
<textarea rows="20" cols="60" id="showChat" readonly="readonly"></textarea><br>
<input type="text" id="chatInfo" style="width:300px;height:25px">
<input type="button" value=" 发送 " onclick="sendMsg()">
</div>
</form>
</body>
</html>

  ChatServlet

import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial")
public class ChatServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String chatMsg = request.getParameter("chatMsg");
ChatService chatService = ChatService.getChat();
if(null!=chatMsg && chatMsg.trim().length()>0){
chatService.addMsg(chatMsg, request.getRemoteAddr());
String getMsg = chatService.getMsg();
out.print(getMsg);
}else{
String getMsg = chatService.getMsg();
out.print(getMsg);
}
}
}

  ChatService

import java.util.LinkedList;

public class ChatService {
private static ChatService chat;
private LinkedList<String> list;
private ChatService(){} public static ChatService getChat(){
if(chat==null){
chat = new ChatService();
}
return chat;
} public void addMsg(String Msg,String uname){
if(list==null){
list = new LinkedList<String>();
}
if(list.size()>10){
list.removeFirst();
}
list.add(uname+"说:"+Msg); } public String getMsg(){ String Msg = "";
if(list!=null){
for (String str:list) {
Msg+=(str+"\n");
}
}
return Msg;
}
}

  结果截图:

Ajax聊天的更多相关文章

  1. PHP+ajax聊天室源码!支持长轮循跟定时请求两种

      var lastID = "1";//声明上次取回的消息的ID var isposted = false; var mGetTime;//设置setTimeout的返回值 // ...

  2. WebForm+一般处理程序+Ajax聊天

    #### 很容易理解 插入数据 到数据库 在使用 setInterval() 读取数据 显示在 页面中 好了 不废话 直接上代码 不会的 可以加我 微信 Jth11163## 效果图片 ![在这里插入 ...

  3. Ajax PHP JavaScript MySQL实现简易的无刷新在线聊天室

    思路 消息显示区 发消息 板块 消息显示 消息发送 优化 显示非重复性的数据 优化显示 加上滚动条 每次都显示最新消息 完整代码 前端代码 数据库表结构 服务器端代码 总结与展望 总结 展望 为更好的 ...

  4. 第六章 jQuery和ajax应用

    ajax是异步JavaScript和xml的简称. 一. ajax补白 优势 不足(不一定是不足) 不需要任何插件(但需要浏览器支持js) XMLHttpRequest对象在不同浏览器下有差异 优秀的 ...

  5. 《锋利的JQuery》读书要点笔记5——jQuery与Ajax的应用

    第6章 jQuery与Ajax的应用 Ajax的全称:Asynchronous JavaScript and XML (异步Javascript和XML) 传统模式中,数据提交通过表单方式实现,数据的 ...

  6. Python(九)Tornado web 框架

    一.简介 Tornado 是 FriendFeed 使用的可扩展的非阻塞式 web 服务器及其相关工具的开源版本.这个 Web 框架看起来有些像web.py 或者 Google 的 webapp,不过 ...

  7. Json学习笔记

    一.昨天内容回顾 创建ajax对象 a) 主流浏览器  new  XMLHttpRequest(); b) IE浏览器  new ActiveXObject("Msxml2.XMLHTTP. ...

  8. Tornado web 框架

    Tornado web 框架 其实很简单.深度应用 一.简介 Tornado 是 FriendFeed 使用的可扩展的非阻塞式 web 服务器及其相关工具的开源版本.这个 Web 框架看起来有些像we ...

  9. 100本最棒的web前端图书推荐

    前端技术,要学习的内容太多了,当你不知道从哪里开始的时候,你就先从看书开始,边看书边码代码,这个是学习编程必须的过程,因为你看一百遍,还不如自己写一遍,写一遍,第一可以加印象,第二便于更好的理解. 熟 ...

随机推荐

  1. virtualenv 安装 lxml

    sudo apt-get install zlib1g-dev sudo apt-get install lib32z1-dev sudo apt-get install libxml2-dev li ...

  2. ios学习-制作一个浏览图片的Demo

    一.项目要求:制作一个浏览图片的Demo,要求包含夜间模式,以及改变图片大小,能够显示不同的图片描述 二.开发步骤: 1.在storyboard上添加一个空白的View,然后添加”设置“按钮,添加im ...

  3. 在.NET中使用JQuery 选择器精确提取网页内容

    1. 前言 相信很多人做开发时都有过这样的需求:从网页中准确提取所需的内容.思前想后,方法无非是以下几种:(本人经验尚浅,有更好的方法还请大家指点) 1. 使用正则表达式匹配所需元素.(缺点:同类型的 ...

  4. Warning: Using a password on the command line interface can be insecure.解决办法

    被一个小朋友问到,直接公布答案: If your MySQL client/server version is a 5.6.x a way to avoid the WARNING message a ...

  5. XPlane android 2D手游开发实战

    android 飞行射击游戏类 采用 xamarin 跨平台开发技术  纯C#语言编写 操作简单 1.手指拖动飞机 躲避敌机 2.通过吃敌机爆炸后遗落的物品增加各种属性 3.双击战机放大技能 4.目前 ...

  6. sql 查询表中所有字段的名称

    最近工作用到SQL语句查询表中所有字段的名称,网上查询,发现不同数据库的查询方法不同,例如: SQL server 查询表的所有字段名称:Select name from syscolumns Whe ...

  7. tomcat端口号被占用

    Eclipse启动TomCat报错:Several ports (8080, 8009) required by Tomcat v8.0 are already in use. Eclipse启动To ...

  8. java如何修改java.library.path并且不重启jvm也能生效

    先说一下需求吧, 目前在用JCEF实现java程序桌面版包装,源码中需要加载编译好的几个dll文件,而这些文件的路径必然是根据程序安装的路径而变化的,这就需要在程序运行的时候,去动态修改java.li ...

  9. Node.js怎么处理数据库中日期类型

    问题描述:在数据库里存储时间的时候明明显示的是类如2016-12-22的形式,读取出来后却变成了大概是这样的:Fri May 17 2016 14:12:33 GMT+0800 (中国标准时间) 处理 ...

  10. libevent源码分析:signal-test例子

    signal-test是libevent自带的一个例子,展示了libevent对于信号事件的处理方法. #include <sys/types.h> #include <event2 ...