结构:

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. (五)SQL入门 数据库查询

    什么是查询?查询就是Select语句对数据库的探究. 查询是一种目的,一种需求,一种期望.是Select语句去实现的.Select语句不是只是指select语句,而是多个子句一起使用得组合. sele ...

  2. DELPHI XE5

    一直觉得DELPHI7之后,如果写WINDOWS桌面应用,没什么变化. 一直在痛苦,为什么DELPHI提供的控件那么丑陋,透明等什么功能都做的那么差. 一直在郁闷,新装的DELPHI都不带DEMO. ...

  3. AngularJs--angular-pagination可复用的分页指令

    1.angular-pagination 是基于angular 编写的可复用分页指令 安装 克隆项目到本地: git clone https://github.com/febobo/angular-p ...

  4. PHP基础班初学感悟

    不知不觉差不多一个月就过去了 刚到培训班那时候的心情,现在也还能有所感觉 作为今年6月份的毕业生,刚从大学的实习期出来,辞掉了上一份工作,本来是打算找一份更加与专业挂钩的工作做的 也许是90后对网络的 ...

  5. 在SQL Server 2005中连接Oracle,完成查询、插入操作

    建立指向Oracle的连接假设Oracle数据库的用户名为test,密码为test,在SQL Server数据库所在服务器上建立的指向Oracle数据库的服务命名为hisorcl.1. 在SQL Se ...

  6. Java反射遍历数组

    日志中有时候需要查看数组中的值,但是重载很多的打印函数,觉得很别扭.所以想通过反射,获取数组中的值,打印出来.Java提供了数组反射操作的类,之前没有关注过,提供的方法简单易用. public sta ...

  7. JAG Summer 2012 Day 4 C Connect

    状压dp,由于枚举两维状态会GG,所以只枚举当前位置前m个的状态,就是这个样子大概= =: 呆马: #include <iostream> #include <cstdio> ...

  8. gerrit session expired 怎么解决,搜索未果

    gerrit session expired,怎么解决,搜索未果

  9. Java中货币格式化

    private final static NumberFormat CURRENCY_FORMAT = NumberFormat.getCurrencyInstance(Locale.CHINA); ...

  10. CentOS 6.5 安装HDFS集群(Hadoop-2.7.3)

    安装真实集群,而不是但节点或者伪分布式,以3个节点为例,node1为NameNode和SecondNameNode,node2和node3为DataNode. 1.3台机器的配置必须要一模一样,只需要 ...