加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ajax聊天系统

发布时间:2020-12-16 00:29:37 所属栏目:百科 来源:网络整理
导读:目录结构: 代码如下:chat.html !DOCTYPE htmlhtmlheadmeta name="author" content="Yeeku.H.Lee(CrazyIt.org)" /meta http-equiv="Content-Type" content="text/html; charset=GBK" /title聊天页面/title/headbody onload="sendEmptyRequest();"div style=

目录结构:


代码如下:chat.html

<!DOCTYPE html>
<html>
<head>
	<meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" />
	<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
	<title>聊天页面</title>
</head>
<body onload="sendEmptyRequest();">
<div style="width:780px;border:1px solid black;text-align:center">
<h3>聊天页面</h3>
<p>
<textarea id="chatArea" name="chatArea" cols="90"
	rows="30" readonly="readonly"></textarea>
</p>
<div align="center">
	<input id="chatMsg" name="chatMsg" type="text"
	size="90" onkeypress="enterHandler(event);"/>
	<input type="button" name="button" value="提交"
	onclick="sendRequest();"/>
</div>
</div>
<script type="text/javascript">
var input = document.getElementById("chatMsg");
input.focus();
var XMLHttpReq;
// 创建XMLHttpRequest对象   
function createXMLHttpRequest()
{
	if(window.XMLHttpRequest)
	{ 
		// DOM 2浏览器
		XMLHttpReq = new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
		// IE浏览器
		try
		{
			XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
			}
		}
	}
}
// 发送请求函数
function sendRequest()
{
	// input是个全局变量,就是用户输入聊天信息的单行文本框
	var chatMsg = input.value;
	// 完成XMLHttpRequest对象的初始化
	createXMLHttpRequest();
	// 定义发送请求的目标URL
	var url = "chat.do";
	// 通过open方法取得与服务器的连接
	// 发送POST请求
	XMLHttpReq.open("POST",url,true);
	// 设置请求头-发送POST请求时需要该请求头
	XMLHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	// 指定XMLHttpRequest状态改变时的处理函数
	XMLHttpReq.onreadystatechange = processResponse;
	// 清空输入框的内容
	input.value = "";
	// 发送请求,send的参数包含许多的key-value对。
	// 即以:请求参数名=请求参数值 的形式发送请求参数。
	XMLHttpReq.send("chatMsg=" + chatMsg); 
}

function sendEmptyRequest()
{
	// 完成XMLHttpRequest对象的初始化
	createXMLHttpRequest();
	// 定义发送请求的目标URL
	var url = "chat.do";
	// 发送POST请求
	XMLHttpReq.open("POST","application/x-www-form-urlencoded");
	// 指定XMLHttpRequest状态改变时的处理函数
	XMLHttpReq.onreadystatechange = processResponse;
	// 发送请求,,不发送任何参数
	XMLHttpReq.send(null);
	// 指定0.8s之后再次发送请求
	setTimeout("sendEmptyRequest()",800);
}
// 处理返回信息函数
function processResponse()
{
	// 当XMLHttpRequest读取服务器响应完成
	if (XMLHttpReq.readyState == 4)
	{
		// 服务器响应正确(当服务器响应正确时,返回值为200的状态码)
		if (XMLHttpReq.status == 200)
		{
			// 使用chatArea多行文本域显示服务器响应的文本
			document.getElementById("chatArea").value 
				= XMLHttpReq.responseText;
		}
		else
		{
			// 提示页面不正常
			window.alert("您所请求的页面有异常。");
		}
	}
}

function enterHandler(event)
{
	// 获取用户单击键盘的“键值”
	var keyCode = event.keyCode ? event.keyCode 
		: event.which ? event.which : event.charCode;
	// 如果是回车键
	if (keyCode == 13)
	{
		sendRequest();
	}
}
</script>
</body>
</html>






charreply.jsp

<%@ page contentType="text/html;charset=GBK" errorPage="error.jsp"%>
<%-- 输出当前的聊天信息 --%>
${requestScope.chatList}

error.jsp

<%--
网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
author yeeku.H.lee kongyeeku@163.com
version 1.0
Copyright (C),2001-2014,yeeku.H.Lee
This program is protected by copyright laws.
Program Name:
Date: 
--%>

<%@ page contentType="text/html;charset=GBK" isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
	<meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" />
	<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
	<title> 系统出现异常 </title>
</head>
<body>
系统出现如下异常:<br/>
<hr/>
${exception}
</body>
</html>


index.jsp

<%--
网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
author yeeku.H.lee kongyeeku@163.com
version 1.0
Copyright (C),yeeku.H.Lee
This program is protected by copyright laws.
Program Name:
Date: 
--%>

<%@ page contentType="text/html;charset=GBK" errorPage="error.jsp"%>
<!DOCTYPE html>
<html>
<head>
	<meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" />
	<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
	<title> 登录系统 </title>
</head>
<body>
<center>
<div style="width:540px;border:1px solid black;background-color:#ddd;">
<form id="loginForm" method="post" action="login.do">
<span style="color:red">
${requestScope.error}
</span>
<hr/>
<table>
<tr>
	<td colspan="2" align="center">
		请输入用户名和密码登录
	</td>
</tr>
<tr>
	<td>用户名:</td>
	<td><input id="name" type="text" name="name" /></td>  <!-- required="true" -->
</tr>
<tr>
	<td>密码:</td>
	<td><input id="pass" type="text" name="pass"  /></td>
</tr>
<tr>
	<td colspan="2" align="center">
		<input type="submit" value="提交"/>
		<input type="reset" value="重设"/>
	</td>
</tr>
</table>
<br/>
<div align="center">
<a href="reg.jsp">注册新用户</a>
</div>
</form>
</div>
</center>
<script type="text/javascript">
	// 自定义用户函数,该函数用于完成基本的客户端数据校验
	function check()
	{
		//alert("jjj");
		// 获取文档中的用户名文本框对象
		var name = document.getElementById("name");
		// 获取文档中的密码文本框对象
		var pass = document.getElementById("pass");
		var errStr = "";
		// 当用户名为空时
		if (name.value == "" || name.value == null)
		{
			// 添加错误提示字符串
			errStr += "用户名不能为空n";
		}
		// 当密码为空时
		if (pass.value == "" || pass.value == null)
		{
			//添加错误提示字符串
			errStr += "密码不能为空n";
		}
		// 如果错误提示字符串为空,表明用户名、密码都已经输入
		if (errStr == "" || errStr == null)
		{
			return true;
		}
		// 否则弹出错误提示
		alert(errStr);
		// 拒绝提交表单
		return false;
	}
	// 关联表单提交与数据校验函数
	document.getElementById("loginForm").onsubmit = check;
</script>
</body>
</html>


reg.jsp


<%--
网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
author yeeku.H.lee kongyeeku@163.com
version 1.0
Copyright (C),yeeku.H.Lee
This program is protected by copyright laws.
Program Name:
Date: 
--%>

<%@ page contentType="text/html;charset=GBK" errorPage="error.jsp"%>
<!DOCTYPE html>
<html>
<head>
	<meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" />
	<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
	<title> 注册用户 </title>
</head>
<body>
<center>
<div style="width:540px;border:1px solid black;background-color:#ddd">
<form id="regForm" method="post" action="reg.do">
<span style="color:red">
${requestScope.tip}
</span>
<hr/>
<table>
<tr>
	<td colspan="2" align="center">
		请输入用户名和密码完成注册
	</td>
</tr>
<tr>
	<td>用户名:</td>
	<td><input id="name" type="text" name="name" required="true"/></td>
</tr>
<tr>
	<td>密码:</td>
	<td><input id="pass" type="password" name="pass" required="true"/></td>
</tr>
<tr>
	<td colspan="2" align="center">
		<input type="submit" value="提交"/>
		<input type="reset" value="重设"/>
	</td>
</tr>
</table>
<br/>
<div align="center">
	<a href="index.jsp">登录</a>
</div>
</form>
</div>
</center>
<script type="text/javascript">
	function check()
	{
		var name = document.getElementById("name");
		var pass = document.getElementById("pass");
		var errStr = "";
		if (name.value == "" || name.value == null)
		{
			errStr += "用户名不能为空n";
		}
		if (pass.value == "" || pass.value == null)
		{
			errStr += "密码不能为空n";
		}
		if (errStr == "" || errStr == null)
		{
			return true;
		}
		alert(errStr);
		return false;
	}
	document.getElementById("regForm").onsubmit = check;
</script>
</body>
</html>



ChatService.java

package org.crazyit.chat.service;

import java.util.*;
import java.io.*;

/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C),Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author Yeeku.H.Lee kongyeeku@163.com
 * @version 1.0
 */
public class ChatService
{
	// 使用单例模式来设计ChatService
	private static ChatService cs;
	// 使用Properties对象保存系统的所有用户
	private Properties userList;
	// 使用LinkedList对象保存聊天信息
	private LinkedList<String> chatMsg;
	// 构造器私有
	private ChatService()
	{
	}
	// 通过静态方法返回唯一的ChatService对象
	public static ChatService instance()
	{
		if (cs == null)
		{
			cs = new ChatService();
		}
		return cs;
	}
	// 验证用户的登录
	public boolean validLogin(String user,String pass)
		throws IOException
	{
		// 根据用户名获取密码
		String loadPass = loadUser().getProperty(user);
		// 登录成功
		if (loadPass != null
			&& loadPass.equals(pass))
		{
			return true;
		}
		return false;
	}
	// 新注册用户
	public boolean addUser(String name,String pass)
		throws Exception
	{
		// 当userList为null,初始化userList对象
		if (userList == null)
		{
			userList = loadUser();
		}
		// 如果userList已经所需注册的用户
		if (userList.containsKey(name))
		{
			throw new Exception("用户名已经存在,请重新选择用户名");
		}
		userList.setProperty(name,pass);
		saveUserList();
		return true;
	}
	// 获取系统中所有聊天信息
	public String getMsg()
	{
		// 如果chatMsg对象为null,表明不曾开始聊天
		if(chatMsg == null)
		{
			chatMsg = new LinkedList<>();
			return "";
		}
		StringBuilder result = new StringBuilder();
		// 将chatMsg中所有聊天信息拼接起来。
		for (String line : chatMsg)
		{
			result.append(line + "n");
		}
		return result.toString();
	}
	// 用户发言,添加聊天信息
	public void addMsg(String user,String msg)
	{
		// 如果chatMsg对象为null,初始化chatMsg对象
		if (chatMsg == null)
		{
			chatMsg = new LinkedList<>();
		}
		// 最多保存40条聊天信息,当超过40条之后,将前面聊天信息删除
		if (chatMsg.size() > 40)
		{
			chatMsg.removeFirst();
		}
		//添加新的聊天信息
		chatMsg.add(user + "说:" + msg);
	}
	//------------下面是系统的工具方法--------------
	// 读取系统用户信息
	private Properties loadUser() throws IOException
	{
		if (userList == null)
		{
			// 加载userFile.properties文件
			File f = new File("userFile.properties");
			// 如果文件不存在,新建该文件
			if (!f.exists())
			{
				f.createNewFile();
			}
			// 新建Properties文件
			userList = new Properties();
			// 读取userFile.properties文件里的用户信息
			userList.load(new FileInputStream(f));
		}
		return userList;
	}
	// 保存系统所有用户
	private boolean saveUserList() throws IOException
	{
		if (userList == null)
		{
			return false;
		}
		// 将userList信息保存到Properties文件中
		userList.store(new FileOutputStream("userFile.properties"),"Users Info List");
		return true;
	}
}

ChatServlet.java

package org.crazyit.chat.web;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

import java.io.*;

import org.crazyit.chat.service.*;

 
@WebServlet(urlPatterns={"/chat.do"})
public class ChatServlet extends HttpServlet
{
	public void service(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException
	{
		// 设置使用GBK字符集来解析请求参数
		request.setCharacterEncoding("utf-8");
		String msg = request.getParameter("chatMsg");
		if ( msg != null && !msg.equals(""))
		{
			// 取得当前用户
			String user = (String)request.getSession(true)
				.getAttribute("user");
			// 调用ChatService的addMsg来添加聊天消息
			ChatService.instance().addMsg(user,msg);
		}
		// 将全部聊天信息设置成request属性
		request.setAttribute("chatList",ChatService.instance().getMsg());
		// 转发到chatreply.jsp页面
		forward("/chatreply.jsp",request,response);
	}
	// 执行转发请求的方法
	private void forward(String url,HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
	{
		// 执行转发
		request.getRequestDispatcher(url)
			.forward(request,response);
	}
}


LoginServlet.java

package org.crazyit.chat.web;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

import java.io.IOException;

import org.crazyit.chat.service.*;

 
@WebServlet(urlPatterns={"/login.do"})
public class LoginServlet extends HttpServlet
{
	public void service(HttpServletRequest request,ServletException
	{
		// 设置使用GBK字符集来解析请求参数
		request.setCharacterEncoding("GBK");
		// 取得用户的两个请求参数
		String name = request.getParameter("name");
		String pass = request.getParameter("pass");
		// 进行服务器端的输入校验
		if (name == null || name.trim().equals("")
			|| pass == null || pass.trim().equals(""))
		{
			request.setAttribute("tip","用户名和密码都不能为空");
			forward("/index.jsp",response);
		}
		else
		{
			// 调用ChatService对象的validLogin方法来验证登录
			// 如果登录成功
			if (ChatService.instance().validLogin(name,pass))
			{
				request.getSession(true).setAttribute("user",name);
				request.setAttribute("msg",ChatService.instance().getMsg());
				forward("/chat.html",response);
			}
			// 如果登录失败
			else
			{
				request.setAttribute("error","用户名和密码不匹配");
				forward("/index.jsp",response);
			}
		}
	}
	// 执行转发请求的方法
	private void forward(String url,response);
	}
}

RegServlet.java

package org.crazyit.chat.web;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

import java.io.IOException;

import org.crazyit.chat.service.*;

 
@WebServlet(urlPatterns={"/reg.do"})
public class RegServlet extends HttpServlet
{
	public void service(HttpServletRequest request,"必填项不能为空");
		}
		else
		{
			try
			{
				// 调用ChatService对象的addUser方法来增加用户
				// 如果注册成功
				if(ChatService.instance().addUser(name,pass))
				{
					request.setAttribute("tip","注册成功,请登录系统");
				}
				// 如果注册失败
				else
				{
					request.setAttribute("tip","无法正常注册,请重试");
				}
			}
			catch(Exception e)
			{
				request.setAttribute("tip",e.getMessage());
			}
		}
		forward("/reg.jsp",response);
	}
}


源代码下载地址: http://download.csdn.net/detail/itjavawfc/7590041

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读