基于ajax的聊天室的小型模板,采用JSON格式;后台为jsp
星期三, 2009-03-11 | Author: Lee | ajax, JAVA-and-J2EE | 9,086 views
这个小型应用中包含了几个非常常用的处理方式,对纯粹手工写个ajax应用有一定的帮助,留个方便自己以后直接小型应用(非框架版)代码如下:
数据库的表是mysql的:如下
1 2 3 4 5 6 | CREATE TABLE 'chatmessage'( 'id' int(11) NOT NULL auto_increment, 'username' varchar(255) NOT NULL, 'message' text, PRIMARY KEY('id') ) |
静态页面:chatroom.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>聊天室</title> <style type="text/css"> /* 页面字体样式 */ body, td, input { font-family:Arial; font-size:12px; } /* 显示发言信息 */ #msgDiv { height:300px; border:1px solid black; overflow:scroll; } </style> <script type="text/javascript"> var xmlHttp; var userName; //用于保存当前登录用户名 var lastId = 0; //用于保存最后读取的聊天记录编号 var newMsgTimer; //用于保存刷新消息计时器 //用于创建XMLHttpRequest对象 function createXmlHttp() { if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } else { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } } //聊天用户登录 function login() { userName = document.getElementById("userName").value; if (userName=="") { alert("请输入您的昵称。"); } else { document.getElementById("loginDiv").style.display = "none"; //隐藏登录div document.getElementById("chatDiv").style.display = ""; //显示聊天div getNewMessage(); //获取新信息 } } //用户发言 function sendMessage() { var msg = document.getElementById("msg").value; //获取用户发言内容 //当内容为空时,提示用户 if (msg == "") { alert("发言不可为空。"); } else { document.getElementById("msg").value = ""; //清除用户发言 clearInterval(newMsgTimer); //清除获取新消息计时器 createXmlHttp(); xmlHttp.onreadystatechange = writeNewMessage; xmlHttp.open("POST", "chatroom.jsp", true); //发送POST请求 xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlHttp.send("action=send" + "&userName=" + encodeURIComponent(userName) + "&msg=" + encodeURIComponent(msg) + "&lastId=" + lastId); //参数包含用户信息和发言内容 } } //获取最新发言 function getNewMessage() { createXmlHttp(); xmlHttp.onreadystatechange = writeNewMessage; xmlHttp.open("POST", "chatroom.jsp", true); xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlHttp.send("action=get&lastId=" + lastId); } //将服务器返回的最新发言写入页面 function writeNewMessage(newMsg) { if (xmlHttp.readyState == 4) { var msgDiv = document.getElementById("msgDiv"); var newMsgObj = eval("("+xmlHttp.responseText+")"); //当最后发言编号大于当前lastId时,在页面写入新内容 if (newMsgObj.lastId > lastId) { lastId = newMsgObj.lastId; //更新lastId msgDiv.innerHTML += newMsgObj.msg; //追加新内容 msgDiv.scrollTop = msgDiv.scrollHeight; //滚动div内容到底部 } newMsgTimer = setTimeout("getNewMessage();", 1000); //1秒后获取新发言 } } //判断用户输入 function checkEnter(evt) { var code = evt.keyCode||evt.which; //如果用户输入回车,调用sendMessage函数 if (code == 13) { sendMessage(); } } </script> </head> <body> <h1>聊天室</h1> <div id="loginDiv"> 昵称:<input type="text" id="userName"> <input type="button" value="登录聊天室" onclick="login()"> </div> <div id="chatDiv" style="display:none"> <div id="msgDiv"></div> <div id="sendDiv"> <input type="text" id="msg" size="30" onkeypress="checkEnter(event)"> <input type="button" value="发送" onclick="sendMessage()"> </div> </div> </body> </html> |
后台的jsp页面code:chatroom.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | <%@ page contentType="text/html; charset=UTF-8"%> <%@ page language="java"%> <%@ page import="java.sql.*,ajax.db.DBUtils"%> <% request.setCharacterEncoding("UTF-8"); out.clear(); String action = request.getParameter("action"); int lastId = Integer.parseInt(request.getParameter("lastId")); if ("send".equals(action)) { String userName = request.getParameter("userName"); String msg = request.getParameter("msg"); String insertSql = "insert into chatmsg(username, message) values (?,?)"; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = DBUtils.getConnection(); pstmt = conn.prepareStatement(insertSql); pstmt.setString(1, userName); pstmt.setString(2, msg); pstmt.executeUpdate(); } catch (SQLException e) { System.out.println(e.toString()); } finally { DBUtils.close(rs); DBUtils.close(pstmt); DBUtils.close(conn); } } String sql = "select * from chatmsg where id > ? order by id asc"; StringBuffer newMsg = new StringBuffer("{'msg':'"); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = DBUtils.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setInt(1, lastId); rs = pstmt.executeQuery(); while (rs.next()) { lastId = rs.getInt("id"); newMsg.append("<div class=\"oneMsg\"><span class=\"userName\">"); newMsg.append(rs.getString("username")); newMsg.append("</span> 说:"); newMsg.append(rs.getString("message")); newMsg.append("</div>"); } } catch (SQLException e) { System.out.println(e.toString()); } finally { DBUtils.close(rs); DBUtils.close(pstmt); DBUtils.close(conn); } newMsg.append("','lastId':"); newMsg.append(lastId); newMsg.append("}"); out.print(newMsg.toString()); %> |
文章作者: Lee
本文地址: https://www.pomelolee.com/339.html
除非注明,Pomelo Lee文章均为原创,转载请以链接形式标明本文地址
2 Comments to 基于ajax的聊天室的小型模板,采用JSON格式;后台为jsp
请问DBUtils如何引入
liyz
2009 年 03 月 30 日
2009 年 03 月 30 日
DBUtils 就是处理数据的CRUD工具类,比较简单就没有放上来
Leave a comment
Search
相关文章
热门文章
最新文章
文章分类
- ajax (10)
- algorithm-learn (3)
- Android (6)
- as (3)
- computer (85)
- Database (30)
- disucz (4)
- enterprise (1)
- erlang (2)
- flash (5)
- golang (3)
- html5 (18)
- ios (4)
- JAVA-and-J2EE (186)
- linux (143)
- mac (10)
- movie-music (11)
- pagemaker (36)
- php (50)
- spring-boot (2)
- Synology群晖 (2)
- Uncategorized (6)
- unity (1)
- webgame (15)
- wordpress (33)
- work-other (2)
- 低代码 (1)
- 体味生活 (40)
- 前端 (21)
- 大数据 (8)
- 游戏开发 (9)
- 爱上海 (19)
- 读书 (4)
- 软件 (3)
2009 年 03 月 28 日