结构:

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. mysql索引的使用和优化

    参考: http://blog.csdn.net/xluren/article/details/32746183 http://www.cnblogs.com/hustcat/archive/2009 ...

  2. winfrom 文字滚动

    winfrom 文字滚动 http://www.codeproject.com/Articles/6913/Creating-a-professional-looking-GDI-drawn-cust ...

  3. php大小写转换

    1.将字符串转换成小写   strtolower();: 该函数将传入的字符串参数所有的字符都转换成小写,并以小定形式放回这个字符串.例: <?php $str = "I want T ...

  4. 关于模拟http请求 cookie的赋值

    最近的工作一直是关于模拟http请求方面的知识的. 原本以为很简单,就是简单模拟一下http请求.先用fiddler模拟一下请求,验证接口可用,就直接上代码. 但是在模拟一个联通http的请求时候,我 ...

  5. IDEA UTF-8 中含 bom 运行报错 批量处理将bom移除

    将eclipse中的项目导入到idea或者as的环境中,遇到UTF-8含有BOM编码报错的问题,之前每次遇到这样的问题都特么用EditPlus一个一个的转换,感觉太烦了,后面就自己写了一个批量处理的工 ...

  6. 《利用python进行数据分析》读书笔记--第八章 绘图和可视化

    http://www.cnblogs.com/batteryhp/p/5025772.html python有许多可视化工具,本书主要讲解matplotlib.matplotlib是用于创建出版质量图 ...

  7. Fragment全解析系列(三):Fragment之我的解决方案:Fragmentation

    源码地址:Github,欢迎Star,Fork. Demo网盘下载(V_0.7.13)Demo演示:单Activity + 多Fragment,项目中有3个Demo. 流式的单Activity+多Fr ...

  8. css样式增加&改变颜色

    .listyle{ color:blue; background-color:red /* background-color:"#006633" */ } .intro{ font ...

  9. Qual F&Q

    [1]长按power键,下面有四个选项可以选择户外,静音,振动标准四种模式 GlobalActions.java->createDialog(): if (!mHasVibrator) { mS ...

  10. dubbo(转载)

    1. Dubbo是什么? Dubbo是一个分布式服务框架,致力于提供高性能和透明化的RPC远程服务调用方案,以及SOA服务治理方案.简单的说,dubbo就是个服务框架,如果没有分布式的需求,其实是不需 ...