结构:

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. Linux下面配置文件~/.bash_profile

    ~/.的意义是什么? ~ 代表你的/home/用户名目录 假设你的用户名是x,那么~/就是/home/x/ . 是代表此目录本身,但是一般可以不写 所以cd ~/. 和cd ~ 和cd ~/效果是一样 ...

  2. Java数据结构之队列的实现以及队列的应用之----简单生产者消费者应用

    Java数据结构之---Queue队列 队列(简称作队,Queue)也是一种特殊的线性表,队列的数据元素以及数据元素间的逻辑关系和线性表完全相同,其差别是线性表允许在任意位置插入和删除,而队列只允许在 ...

  3. Linux_scp

    scp是secure copy的简写,用于在Linux下进行远程拷贝文件的命令,和它类似的命令有cp,不过cp只是在本机进行拷贝不能跨服务器,而且scp传输是加密的.可能会稍微影响一下速度.当你服务器 ...

  4. mysql基础安全

  5. Bash:-:-定义空变量作为输出结合换行符\n和column输出

    RET="" declare -a HOST=() declare -a ALL_SVR=() declare -a FREESVR=() ;i<${#_ALL_AGENT_ ...

  6. 学习激动人心的C++ 11

    1->创建7个Thread,跑个非常大的循环.观察CPU void func(string &name) { ;i<0xFFFFFFFF;i++) { //cout << ...

  7. 关于Java加载属性文件放在web容器不好使的解决办法

    //使用Spring的工具就行了1 import java.util.Properties; import org.springframework.core.io.support.Properties ...

  8. Java Map按键(Key)排序和按值(Value)排序

    Map排序的方式有很多种,两种比较常用的方式:按键排序(sort by key), 按值排序(sort by value).1.按键排序jdk内置的java.util包下的TreeMap<K,V ...

  9. TOJ 2776 CD Making

    TOJ 2776题目链接http://acm.tju.edu.cn/toj/showp2776.html 这题其实就是考虑的周全性...  贡献了好几次WA, 后来想了半天才知道哪里有遗漏.最大的问题 ...

  10. 在jquery的ajax中添加自定义的header信息

    转自网络 1 $.ajax({ type: "POST", url: "http://192.168.0.88/action.cgi?ActionID=WEB_Reque ...