Ajax实现聊天室
Posted 姗姗不来迟
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ajax实现聊天室相关的知识,希望对你有一定的参考价值。
Ajax实现聊天室
运行效果如下:
代码显示:
var net=new Object();
//编写构造函数
net.AjaxRequest=function(url,onload,onerror,method,params){
this.req=null;
this.onload=onload;
this.onerror=(onerror) ? onerror : this.defaultError;
this.loadDate(url,method,params);
}
//编写用于初始化XMLHttpRequest对象并指定处理函数,最后发送HTTP请求的方法
net.AjaxRequest.prototype.loadDate=function(url,method,params){
if (!method){
method="GET";
}
if (window.XMLHttpRequest){
this.req=new XMLHttpRequest();
} else if (window.ActiveXObject){
this.req=new ActiveXObject("Microsoft.XMLHTTP");
}
if (this.req){
try{
var loader=this;
this.req.onreadystatechange=function(){
net.AjaxRequest.onReadyState.call(loader);
}
this.req.open(method,url,true);
if(method=="POST"){
this.req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
}
this.req.send(params);
}catch (err){
this.onerror.call(this);
}
}
}
//重构回调函数
net.AjaxRequest.onReadyState=function(){
var req=this.req;
var ready=req.readyState;
if (ready==4){
if (req.status==200 ){
this.onload.call(this);
}else{
this.onerror.call(this);
}
}
}
//重构默认的错误处理函籹
net.AjaxRequest.prototype.defaultError=function(){
alert("错误数据\\n\\n回调状态:"+this.req.readyState+"\\n状态: "+this.req.status);
}
<script language="javascript" src="JS/AjaxRequest.js"></script>
<script language="javascript">
/******************错误处理的方法*******************************/
function onerror(){
alert("您的操作有误!");
}
/******************实例化Ajax对象的方法*******************************/
function getCheckCode1(showCheckCode,checkCode){
var loader1=new net.AjaxRequest("getPictureCheckCode.jsp?nocache="+
new Date().getTime(),deal_getCheckCode,onerror,"GET");
showCheckCode.style.display=\'\';
checkCode.focus();
}
/************************回调函数**************************************/
function deal_getCheckCode(){
document.getElementById("showCheckCode").innerhtml=this.req.responseText;
}
</script>
ServletContext application = getServletContext();
application.setAttribute(String name,Object object);
name:用于指定一个属性名,该属性在整个Servlet上下文中都适用。
object:用于指定属性值。
application.setAttribute("message", sourceMessage);
application. getAttribute(String name);
name:用于指定一个属性名。
String sourceMessage = application.getAttribute("message").toString();
package com.wgh.model;
import java.util.Vector;
public class UserInfo {
private static UserInfo user = new UserInfo();
private Vector vector = null;
// 利用private定义构造函数,防止被外界产生新的instance对象
public UserInfo() {
this.vector = new Vector();
}
// 外界使用的instance对象
public static UserInfo getInstance() {
return user;
}
// 增加用户
public boolean addUser(String user) {
if (user != null) {
this.vector.add(user);
return true;
} else {
return false;
}
}
// 获取用户列表
public Vector getList() {
return vector;
}
// 移除用户
public void removeUser(String user) {
if (user != null) {
vector.removeElement(user);
}
}
}
package com.wgh.servlet;
import com.wgh.model.UserInfo;
import javax.servlet.http.HttpSessionBindingEvent;
public class UserListener implements
javax.servlet.http.HttpSessionBindingListener {
private String user;
private UserInfo container = UserInfo.getInstance(); //获得UserInfo类的对象
public UserListener() {
user = "";
}
// 设置在线监听人员
public void setUser(String user) {
this.user = user;
}
// 获取在线监听
public String getUser() {
return this.user;
}
// 当Session有对象加入时执行的方法
public void valueBound(HttpSessionBindingEvent arg0) {
System.out.println("上线用户:" + this.user);
}
// 当Session有对象移除时执行的方法
public void valueUnbound(HttpSessionBindingEvent arg0) {
System.out.println("下线用户:" + this.user);
if (user != "") {
container.removeUser(user);
}
}
}
public void loginRoom(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
HttpSession session = request.getSession();
String username=request.getParameter("username"); //获得登录用户名
UserInfo user=UserInfo.getInstance(); //获得UserInfo类的对象
session.setMaxInactiveInterval(600); //设置Session的过期时间为10分钟
Vector vector=user.getList();
boolean flag=true; //标记是否登录的变量
//判断用户是否登录
if(vector!=null&&vector.size()>0){
for(int i=0;i<vector.size();i++){
if(user.equals(vector.elementAt(i))){
PrintWriter out;
try {
out = response.getWriter();
out.println("<script language=\'javascript\'>alert(\'该用户已经登录\');"+
"window.location.href=\'index.jsp\';</script>");
} catch (IOException e) {
e.printStackTrace();
}
flag=false;
break; //跳出for循环
}
}
}
//保存用户信息
if(flag){
UserListener ul=new UserListener(); //创建UserListener的对象
ul.setUser(username); //添加用户
user.addUser(ul.getUser()); //添加用户到UserInfo类的对象中
session.setAttribute("user",ul); //将UserListener对象绑定到Session中
session.setAttribute("username",username); //保存当前登录的用户名
session.setAttribute("loginTime",new Date().toLocaleString()); //保存登录时间
}
ServletContext application=getServletContext(); //获取Application对象
String sourceMessage="";
if(null!=application.getAttribute("message")){
sourceMessage=application.getAttribute("message").toString();
}
sourceMessage+="系统公告:<font color=\'gray\'>" + username + "走进了聊天室!</font><br>";
application.setAttribute("message",sourceMessage);
try {
request.getRequestDispatcher("login_ok.jsp").forward(request, response);
} catch (Exception ex) {
Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, ex);
}
}
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:redirect url="/main.jsp"/>
function showOnline(){
var loader=new net.AjaxRequest("online.jsp?nocache="+
new Date().getTime(),deal_online,onerror,"GET");
}
<%@page contentType="text/html" pageEncoding="UTF-8" %>
<%@ page import="com.wgh.model.UserInfo"%>
<%@ page import="java.util.*"%>
<%
UserInfo list=UserInfo.getInstance();
Vector vector=list.getList();
int amount=0;
%>
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr><td height="32" align="center" class="word_orange ">欢迎来到心之语聊天室!</td></tr>
<tr>
<td height="23" align="center"><a href="#" onclick="set(\'所有人\')">所有人</a></td>
</tr>
<%if(vector!=null&&vector.size()>0){
String username="";
amount=vector.size();
for(int i=0;i<amount;i++){
username=(String)vector.elementAt(i);
%>
<tr>
<td height="23" align="center">
<a href="#" onclick="set(\'<%=username%>\')"><%=username%></a>
</td>
</tr>
<%}}%>
<tr><td height="30" align="center">当前在线[<font color="#FF6600"><%=amount%></font>]人</td></tr>
</table>
<td width="165" valign="top" bgcolor="#f6fded" id="online" style="padding:5px">在线人员列表</td>
function deal_online(){
online.innerHTML=this.req.responseText;
}
window.setInterval("showOnline();",10000);
window.onload=function(){
showOnline(); //当页面载入后显示在线人员列表
}
<script language="javascript">
function set(selectPerson){ //自动添加聊天对象
if(selectPerson!="${username}"){
form1.to.value=selectPerson;
}else{
alert("请重新选择聊天对象!");
}
}
</script>
<a href="#" onclick="set(\'<%=username%>\')"><%=username%></a>
function send(){ //验证聊天信息并发送
if(form1.to.value==""){
alert("请选择聊天对象!");return false;
}
if(form1.content1.value==""){
alert("发送信息不可以为空!");form1.content1.focus();return false;
}
var param="from="+form1.from.value+"&face="+form1.face.value+"&color="+form1.color.value+
"&to="+form1.to.value+"&content="+ form1.content1.value;
var loader=new net.AjaxRequest("Messages?action=sendMessage",deal_send,onerror,"POST",param);
}
public void sendMessages(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
Random random = new Random();
String from = request.getParameter("from"); //发言人
String face = request.getParameter("face"); //表情
String to = request.getParameter("to"); //接收者
String color = request.getParameter("color"); //字体颜色
String content = request.getParameter("content"); //发言内容
String sendTime = new Date().toLocaleString(); //发言时间
ServletContext application = getServletContext();
String sourceMessage = application.getAttribute("message").toString();
try {
//发言时间
sourceMessage += "<font color=\'blue\'><strong>" + from +
"</strong></font><font color=\'#CC0000\'>" + face + "</font>对<font color=\'green\'>[" +
to + "]</font>说:" + "<font color=\'" + color + "\'>" + content + "</font>(" +
sendTime + ")<br>";
application.setAttribute("message", sourceMessage);
request.getRequestDispatcher("Messages?action=getMessages&nocache=" +
random.nextInt(10000)).forward(request, response);
} catch (Exception ex) {
Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, ex);
}
}
function showContent(){
var loader1=new net.AjaxRequest("Messages?action=getMessages&nocache="+
new Date().getTime(),deal_content,onerror,"GET");
}
public void getMessages(HttpServletRequest request,HttpServletResponse response) {
response.setContentType("text/html;charset=UTF-8");
try {
request.getRequestDispatcher("content.jsp").forward(request, response);
} catch (Exception ex) {
Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, ex);
}
}
<%@page contentType="text/html" pageEncoding="UTF-8" %>
${message}
<div style="height:290px; overflow:hidden" id="content">聊天内容</div>
function deal_content(){
var returnValue=this.req.responseText; //获取Ajax处理页的返回值
var h=returnValue.replace(/\\s/g,""); //去除字符串中的Unicode空白符
if(h=="error"){
Exit();
}else{
content.innerHTML=sysBBS+returnValue+"</span>";
//当聊天信息超过一屏时,设置最先发送的聊天信息不显示
document.getElementById(\'content\').scrollTop = document.getElementById(\'content\').scrollHeight*2;
}
}
window.setInterval("showContent();",1000);
window.onload=function(){
showContent(); //当页面载入后显示聊天内容
}
function Exit(){
window.location.href="leave.jsp";
alert("欢迎您下次光临!");
}
<input name="button_exit" type="button" class="btn_grey" value="退出聊天室" onClick="Exit()">
<%@page contentType="text/html" pageEncoding="UTF-8" %>
<%
session.invalidate();
response.sendRedirect("index.jsp");
%>
以上是关于Ajax实现聊天室的主要内容,如果未能解决你的问题,请参考以下文章
基于AJAX的长轮询(long-polling)方式实现简单的聊天室程序