Ajax JSP chat room implementation

Source: Internet
Author: User

Tw-sack.js
/* Simple Ajax code-kit (sack )*/
/* 2005 Gregory wild-Smith */
/* [Url] www.twilightuniverse.com [/url] */
/* Software licenced under a modified X11 licence, see documentation or authors website for more details */

Function sack (File ){
This. ajaxfailedalert = "your browser does not support the enhanced functionality of this website, and therefore you will have an experience that differs from the intended one./N ";
This. requestfile = file; // submitted page
This. method = "Post ";
This. urlstring = "";
This. encodeuristring = true;
This.exe cute = false;

This. onloading = function () {}; // reading
This. onloaded = function () {}; // read
This. oninteractive = function () {}; // interaction in progress
This. oncompletion = function () {}; // method to be executed after the information is returned
This. Complete = function () {}; // processing completed
This. createajax = function (){
Try {
This. XMLHTTP = new activexobject ("Microsoft. XMLHTTP ");
} Catch (e ){
Try {
This. XMLHTTP = new activexobject ("msxml2.xmlhttp ");
} Catch (ERR ){
This. XMLHTTP = NULL;
}
}
If (! This. XMLHTTP & typeof XMLHttpRequest! = "Undefined ")
This. XMLHTTP = new XMLHttpRequest ();
If (! This. XMLHTTP ){
This. Failed = true;
}
};

This. setvar = function (name, value ){
If (this. urlstring. Length <3 ){
This. urlstring = Name + "=" + value;
} Else {
This. urlstring + = "&" + name + "=" + value;
}
}

This. encvar = function (name, value ){
VaR varstring = encodeuricomponent (name) + "=" + encodeuricomponent (value );
Return varstring;
}

This. encodeurlstring = function (string ){
Vararray = string. Split ('&');
For (I = 0; I <vararray. length; I ++ ){
Urlvars = vararray [I]. Split ('= ');
If (urlvars [0]. indexof ('amp ;')! =-1 ){
Urlvars [0] = urlvars [0]. substring (4 );
}
Vararray [I] = This. encvar (urlvars [0], urlvars [1]);
}
Return vararray. Join ('&');
}

This. runresponse = function (){
Eval (this. Response );
}

This. runajax = function (urlstring ){
This. responsestatus = new array (2 );
If (this. Failed & this. ajaxfailedalert ){
Alert (this. ajaxfailedalert );
} Else {
If (urlstring ){
If (this. urlstring. Length ){
This. urlstring = This. urlstring + "&" + urlstring;
} Else {
This. urlstring = urlstring;
}
}
If (this. encodeuristring ){
VaR timeval = new date (). gettime ();
This. urlstring = This. encodeurlstring (this. urlstring );
This. setvar ("rndval", timeval );
}
If (this. element) {This. elementobj = Document. getelementbyid (this. element );}
If (this. XMLHTTP ){
VaR self = this;
If (this. Method = "get "){
VaR totalurlstring = This. requestfile + "? "+ This. urlstring;
This. XMLHTTP. Open (this. method, totalurlstring, true );
} Else {
This. XMLHTTP. Open (this. method, this. requestfile, true );
}
If (this. Method = "Post "){
Try {
This. XMLHTTP. setRequestHeader ('content-type', 'application/X-WWW-form-urlencoded; charset = UTF-8 ')
} Catch (e ){}
}

This. XMLHTTP. Send (this. urlstring );
This. XMLHTTP. onreadystatechange = function (){
Switch (self. XMLHTTP. readystate ){
Case 1: // reading
Self. onloading ();
Break;
Case 2: // read
Self. onloaded ();
Break;
Case 3: // interaction in progress
Self. oninteractive ();
Break;
Case 4: // processing is complete
Self. Response = self. XMLHTTP. responsetext;
Self. responsexml = self. XMLHTTP. responsexml;
Self. responsestatus [0] = self. XMLHTTP. status;
Self. responsestatus [1] = self. XMLHTTP. statustext;
Self. oncompletion ();
If(self.exe cute) {self. runresponse ();}
If (self. elementobj ){
VaR elemnodename = self. elementobj. nodename;
Elemnodename. tolowercase ();
If (elemnodename = "input" | elemnodename = "select" | elemnodename = "option" | elemnodename = "textarea "){
Self. elementobj. value = self. response;
} Else {
Self. elementobj. innerhtml = self. response;
}
}
Self. urlstring = "";
Self. Complete ();
Break;
}
};
}
}
};
This. createajax ();
}

Display. js
Function overinput (){
GETID ("BTN"). style. Border = "1px solid #54ce43"
GETID ("content"). style. Border = "1px solid #54ce43"
Focs ()
}
Function outinput (){
GETID ("BTN"). style. Border = "1px solid # AAA"
GETID ("content"). style. Border = "1px solid # AAA"
Focs ()
}
Function overbtn (){
A. src = "images/hover.gif"
}
Function outbtn (){
A. src = "images/rest.gif"
}
Function lrover (){
A. style. backgroundcolor = "# Eee"
}
Function lrout (){
A. style. backgroundcolor = "# fff"
}
Function focs (){
Getname ("content"). Focus ();
}
Function clean (){
Getname ("content"). value = ""
}
VaR chats = new array ()
VaR chatstart
Function addchat (strchat ){
If (chats. length> 199 ){
Chats. Shift ()
}
Chats. Push (strchat)
Chatstart = chats. Length
}
Function prechat (){
If (chatstart & chatstart> = 1 ){
If (chatstart = 1 ){
Getname ("content"). value = chats [0]
Chatstart = 0.5
} Else {
Chatstart-= 1
Getname ("content"). value = chats [chatstart]
}
}
GETID ("loadifo"). innerhtml = chatstart + "," + chats. Length
}
Function nextchat (){
If (chatstart & chatstart <chats. Length & chats. length> 1 ){
If (chatstart = 0.5 ){
Chatstart = 1
} Else if (chatstart = chats. Length-1 ){
Chatstart = chats. Length-1
} Else {
Chatstart + = 1
}
Getname ("content"). value = chats [chatstart]
}
GETID ("loadifo"). innerhtml = chatstart + "," + chats. Length
}
Window. onload = function (){
GETID ("outs"). onmousedown = function (){
Overs = 1
}
GETID ("outs"). onmouseout = function (){
Overs = 0
Focs ()
}
Getname ("content"). onkeydown = function (e ){
If (document. All ){
VaR keys = event. keycode;
} Else {
VaR keys = E. Which;
}
// Alert (keys)
If (Keys = "38 "){
Prechat ()
} Else if (Keys = "40 "){
Nextchat ()
} Else if (event. ctrlkey & keys = "13 "){
Dousingpost ()
} Else if (event. ctrlkey & keys = "46 "){
Clean ()
}
}

}
Function GETID (objid ){
Return document. getelementbyid (objid)
}
Function getname (objname ){
Return document. getelementsbyname (objname) [0]
}

Chat. js
VaR overs;
VaR clien = 0;
Function dousingget (){
VaR Ajax = new sack ("chat. jsp ");
Ajax. setvar ("clien", clien );
Ajax. setvar ("timestamp", new date (). gettime ());
Ajax. method = 'get ';
Ajax. onloading = function (){
Document. getelementbyid ("ZT"). innerhtml = "reading ......";
}
Ajax. oncompletion = function () {// method executed after information is returned
Checkstate(ajax.responsexml.doc umentelement );
}
Ajax. onloaded = function (){
Document. getelementbyid ("ZT"). innerhtml = "read ......";
}
Ajax. oninteractive = function (){
Document. getelementbyid ("ZT"). innerhtml = "interaction ......";
}
Ajax. Complete = function (){
Document. getelementbyid ("ZT"). innerhtml = "processing completed ......";
}
Ajax. runajax ();
}
Function dousingpost (){
If (getname ("content"). value! = ""){
VaR named = getname ("named"). value;
VaR content = getname ("content"). value;
VaR Ajax = new sack ("chat. jsp ");
Ajax. setvar ("clien", clien );
Ajax. setvar ("content", content );
Ajax. setvar ("named", named );
Ajax. setvar ("timestamp", new date (). gettime ());
Ajax. method = 'post ';
Ajax. onloading = function (){
Document. getelementbyid ("ZT"). innerhtml = "reading ......";
}
Ajax. oncompletion = function () {// method executed after information is returned
Checkstate(ajax.responsexml.doc umentelement );
}
Ajax. onloaded = function (){
Document. getelementbyid ("ZT"). innerhtml = "read ......";
}
Ajax. oninteractive = function (){
Document. getelementbyid ("ZT"). innerhtml = "interaction ......";
}
Ajax. Complete = function (){
Document. getelementbyid ("ZT"). innerhtml = "processing completed ......";
}
Ajax. runajax ();
Focs ();
Clean ();
} Else {
Alert ("Enter the conversation content! ")
Focs ()
}
}

Function checkstate (RES ){
VaR reslen = res. getelementsbytagname ("items"). Length
If (gettag (Res, 0, "num ")! = Clien ){
Clien = gettag (Res, 0, "num ")
For (VAR I = 0; I <reslen; I ++ ){
VaR usename = gettag (Res, I, "name ")
VaR usemag = gettag (Res, I, "conts ")
VaR useip = gettag (Res, I, "ip ")
If (clien! = "0" & usemag! = ""){
If (usename! = ""){
VaR Lis = "user" + usename + "said:" + usemag // + "[" + useip + "]"
} Else {
VaR Lis = "User [" + useip + "]:" + usemag
}
} Else {
VaR Lis = ""
}
GETID ("chatmain"). innerhtml + = Lis + "<br/>"
}
Innersize ()
}
}

Function innersize (){
If (overs! = 1 ){
If (GETID ("chatmain"). offsetheight <GETID ("outmain"). offsetheight ){
GETID ("chatmain"). style. margintop = GETID ("outmain"). offsetheight-GETID ("chatmain"). offsetheight + "PX ";
} Else {
GETID ("chatmain"). scrollintoview (false)
}
}
}
Function gettag (response, I, objtagname ){
Try {
VaR nodev = response. getelementsbytagname (objtagname) [I]. firstchild. nodevalue;
} Catch (e ){
VaR nodev = ""
}
Return nodev;
}
Setinterval ("dousingget ()", 1000)

Chat. jsp
<% @ Page contenttype = "text/XML; charset = gb2312" %>
<%!
String func (string content ){
Return content. replaceall ("<", "<"). replaceall (">", "> ");
}
%>
<%
String IP = request. getremoteaddr (); // Client IP Address
Int clien = new INTEGER (request. getparameter ("clien"). intvalue (); // Number of users currently. If the value is 0, it is the new user.
If (application. getattribute ("counts") = NULL ){
Application. setattribute ("counts", new INTEGER (0 ));
}
Int counts = new INTEGER (application. getattribute ("counts"). tostring (). intvalue (); // the ID of the current user
If (request. getparameter ("content ")! = NULL ){
Synchronized (this ){
If (counts <21 ){
Int I = counts + 1;
Application. setattribute ("counts", new INTEGER (I ));
} Else if (counts> = 21 ){
Application. setattribute ("counts", "1 ");
}
Counts = new INTEGER (application. getattribute ("counts"). tostring (). intvalue (); // the ID of the current user
Int cnum = counts;
String names;
String msgs = request. getparameter ("content ");
// Msgs = new string (MSGs. getbytes ("iso8859-1"), "gb2312 ");
Application. setattribute ("IPS" + cnum, ip );
Application. setattribute ("msgs" + cnum, func (MSGs ));
If (request. getparametervalues ("content ")! = NULL ){
Names = request. getparameter ("named ");
} Else {
Names = "";
}
Application. setattribute ("names" + cnum, names + "");
}
}
%> <? XML version = "1.0" encoding = "gb2312"?>
<Ppl>
<Num> <% = application. getattribute ("counts") %> </num>
<%
If (clien = 0 ){
%>
<Items>
<Ip> <% = IP %> </IP>
</Items>
<%
} Else if (clien <counts ){
For (INT I = clien; I <counts; I ++ ){
Int S = I + 1;
String usename = (string) application. getattribute ("names" + S );
String usemsg = (string) application. getattribute ("msgs" + S );
String useip = (string) application. getattribute ("IPS" + S );
%>
<Items>
<AAA> <% = clien %> <% = S %> </AAA>
<BBB> <% = counts %> </BBB>
<Name> <% = usename %> </Name>
<Conts> <% = usemsg %> </conts>
<Ip> <% = useip %> </IP>
</Items>
<%
}
} Else if (clien> counts ){
For (INT I = clien; I <21; I ++ ){
String usename = (string) application. getattribute ("names" + I );
String usemsg = (string) application. getattribute ("msgs" + I );
String useip = (string) application. getattribute ("IPS" + I );
%>
<Items>
<Name> <% = usename %> </Name>
<Conts> <% = usemsg %> </conts>
<Ip> <% = useip %> </IP>
</Items>
<%
}
For (int m = 1; m <= counts; m ++ ){
String usenamem = (string) application. getattribute ("names" + M );
String usemsgm = (string) application. getattribute ("msgs" + M );
String useipm = (string) application. getattribute ("IPS" + M );
%>
<Items>
<Name> <% = usenamem %> </Name>
<Conts> <% = usemsgm %> </conts>
<Ip> <% = useipm %> </IP>
</Items>
<%
}
} Else if (clien = counts ){

}
%>
</Ppl>

Index.html
<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312"/>
<Title> </title>
<Link href = "images/chatstyle.css" rel = "stylesheet" type = "text/CSS"/>

<SCRIPT type = "text/JavaScript" src = "JS/display. js"> </SCRIPT>
<SCRIPT type = "text/JavaScript" src = "JS/chat. js"> </SCRIPT>
<SCRIPT type = "text/JavaScript" src = "JS/tw-sack.js"> </SCRIPT>

</Head>
<Body>
<Div id = "ZT"> </div>
<Div id = "loadifo"> </div>
<Div id = "outs"> <Div id = "outmain"> <Div id = "chatmain"> </div>
<Div class = "in"> nickname:
<Input class = "names" name = "named" type = "text"/>
<Span id = "inputput" class = "inputput" onmouseover = "overinput (this)" onmouseout = "outinput (this)">
<Input class = "inputs" name = "content" type = "text" Title = "Submit a dialog
Shortcut: enter or Ctrl + enter
Clear
Shortcut Key: Ctrl + Delete "/> <input class =" Left "type =" button "onmouseover =" lrover (this) "value =" "onmouseout =" lrout (this) "onclick =" prechat (); "Title =" previous dialog record
Shortcut: shortcut "/>
<Input class = "right" onmouseover = "lrover (this)" type = "button" value = "" onmouseout = "lrout (this)" onclick = "nextchat (); "Title =" Record of the next Dialog
Shortcut: shortcut "/>
<Input id = "BTN" class = "BTN" type = "image" src = "images/rest.gif" onmouseover = "overbtn (this)" onmouseout = "outbtn (this) "onclick =" dousingpost (); "Title =" Submit a dialog
Shortcut: enter or Ctrl + enter "/>
</Span>
<Span id = "errors"> </span>
</Div>
</Body>
</Html>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.