Problems with developing a chatroom

Hi all,

I am new to jsp and am learning. I need some help. I am developing a chat room application. I am using AJAX to update the screen. Since JSP caches the data, I am using a servlet code for AJAX alone. For others I use JSP as the server coding.

Suppose consider i am logging in as 'user1', I am able to receive other users message only if I trigger any event.

Can you please help me to get others message automatically? Here is my code:

//This jsp code validates the user and provides the chat room screen...

<%--Login validation--%>

<%@ page language="java" %>

<%@ page import="java.sql.*" %>

<%@ page contentType="text/html" %>

<html>

<head>

<title>Login Result</title>

<script src="http://localhost:8080/ChatRoom/ChatScript.js" type="text/javascript"></script>

</head>

<body>

<%

String uid=request.getParameter("id");

String pwd=request.getParameter("pwd");

String tmp_uid="";

String tmp_pwd="";

String welcomeName="";

String onlineMembers="";

String buddyList="";

{

Connection con;

PreparedStatement ps;

ResultSet rs;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con=DriverManager.getConnection("jdbc:odbc:LoginDB");

String str="select * from login where uname=?";

ps=con.prepareStatement(str);

ps.setString(1,uid);

rs=ps.executeQuery();

while(rs.next())

{

tmp_uid = rs.getString("uname");

tmp_pwd = rs.getString("pwd");

welcomeName = rs.getString("fname");

}

if(uid.equals(tmp_uid)&&pwd.equals(tmp_pwd))

{

Cookie ck = new Cookie("user",uid);

response.addCookie(ck);

try{

String setStatus="update login set status='1' where uname=?";

ps=con.prepareStatement(setStatus);

ps.setString(1,uid);

ps.executeQuery();

}catch(Exception e){}

%>

<form method="post" action="logout.jsp">

<%

out.print("Welcome "+welcomeName+" !");

//out.print("<input type=\"hidden\" name=\"username\" value="+uid+">");

%>

<input type="submit" value="Logout"></form><hr>

<%

String checkStatus="select uname from login where status=?";

ps=con.prepareStatement(checkStatus);

ps.setString(1,"1");

rs=ps.executeQuery();

while(rs.next())

{

tmp_uid = rs.getString("uname");

onlineMembers=onlineMembers.concat(tmp_uid+"\n");

}

String friends ="select * from vijay";

ps=con.prepareStatement(friends);

rs=ps.executeQuery();

while(rs.next())

{

String buddy = rs.getString("buddy");

buddyList = buddyList.concat(buddy+"\n");

}

%>

<form action="#" name="chatForm">

Buddy List

<pre><textarea cols=19 rows=20 readonly="readonly" name="BuddyList">

<%

out.println(buddyList);

%>

</textarea> <textarea cols=72 rows=20 readonly="readonly" name="ReceiveText"></textarea> <textarea cols=19 rows=20 readonly="readonly" name="OnlineList">

<%

out.println(onlineMembers);

%>

</textarea></pre>

Type your text here!

<pre><b><textarea cols=90 rows=3 name="SendText"></textarea></b><input type="button" value=" Send " onclick="sendRequest(SendText.value,user.value)"/></pre>

<%

out.print("<input type=\"hidden\" name=\"user\" value="+uid+">");

%>

</form>

<%

}

else

{

%>

<jsp:include page="INVALID_USER_HOME.HTML" flush="true"/>

<%

}

con.close();

}

%>

</body>

</html>

//This is script for AJAX

var request;

var address;

function getRequestObject()

{

if (window.ActiveXObject)

{

return(new ActiveXObject("Microsoft.XMLHTTP"));

}

else if (window.XMLHttpRequest)

{

return(new XMLHttpRequest());

}

else

{

return(null);

}

}

function sendRequest(str,username)

{

address = "http://localhost:8080/ChatServlet/AjaxServer";

address = address+"?text="+str;

address = address+"&name="+username;

request = getRequestObject();

request.onreadystatechange = handleResponse;

if((str.length>0)&&(username.length>0))

{

request.open("GET",address,true);

request.send(null);

}

setTimeout("sendRequest()",500);

}

function handleResponse()

{

if ((request.readyState == 4)&&(request.status == 200))

{

document.chatForm.ReceiveText.value = request.responseText;

document.chatForm.SendText.value = "";

}

}

//This is the servlet for servicing the AJAX requests:

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class ChatServlet extends HttpServlet

{

PrintWriter out;

static String message = "";

String sendText = "";

String name = "";

public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException

{

response.setHeader("Cache-Control", "no-cache");

response.setHeader("Pragma", "no-cache");

response.setContentType("text/html");

sendText = request.getParameter("text");

name = request.getParameter("name");

PrintWriter out = response.getWriter();

java.util.Date d = new java.util.Date();

String date = String.format("(%tr)",d);

message = message.concat(date+name+" : "+sendText+"\n");

out.println(message);

}

}

[5987 byte] By [Vijendrana] at [2007-11-26 13:59:15]
# 1

> Since JSP caches the data, I am using a servlet code for AJAX alone

You do realize that JSP's are translated into servlets by the server when they are first executed? You can send HTTP headers to prevent the browser from caching the page. Something like this:

response.setDateHeader("Expires", 0);

response.setHeader("Pragma", "No-cache");

response.setHeader("Cache-Control", "no-cache");

If you want to update automatically you can use a javascript timer. Just search google for "javascript timer", you'll get loads of examples.

gimbal2a at 2007-7-8 1:39:57 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2

Using a javascript timer is one method to go with.

Another would be the 'Pushlet'. A pushlet is a servlet that never closes the output stream to the client. You would probably make an IFrame or something to that affect that opens up a pushlet servlet. When an incoming message is recieved, your servlet that takes the input forwards to the message to the pushlet which sends the data to the second user -probably using a javascript command.

To make it work you have to hold a map of all the open connections. Your chat request from AJAX would have to identify which open connection(s) get the message.

Look up Pushlets via google.

stevejlukea at 2007-7-8 1:39:57 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 3
thanks for ur suggestion. i wil try and let u know. thank u once again.
Vijendrana at 2007-7-8 1:39:57 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...