Ajax實現聊天室javascript
運行效果以下:html
代碼顯示:java
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");
%>session