http://lvp.javaeye.com/blog/343236, download the attachment provided.
However, this example brought about automatically refresh the page to experience a sense of bad, and when the contents reach the last line of chat, the scroll bar rolling is a very耍赖to solve and, therefore, on this basis, so a number of improvement.
I think, to write code, not necessarily to write a lot of DEMO, but strive to have each of DEMO always better than the previous. May have been written with an example, but each time the realization of a certain improvement in the scrutiny. Therefore, I have been doing such a thing, as far as possible to write each DEMO always better than the last time, always the last to encounter more problems, always the last to know some more to solve these problems way, I think this is a beginner should know a reason. Should not be too greedy and more serious a problem to solve, analyze, and summarize.
So, for me, this example is only an example of better than some, but not the end.
And, in order to download the responsible attitude of friends, all available for download the code must have been the realization of their own hand, not copied from others, the code is complete, it must provide the database on the database, so these codes can help you solve some with similar functionality.
Code description of the red font is the problem I came across, were later resolved, we can see if encountered.
The DEMO, the main solution to these problems the following, or to achieve the following functions.
1. Form of control, only shows the size of a suitable form.
2. Users have landed from the user to check whether the situation of the same name already exists. Ajax call to find the background.
3.后主login form shows that the closure of land form
4. Show are logged, the number of people online, to express our information
5. Information Display, published the news on line and offline, are feeling less than a page refresh, ajax to achieve
6. Scroll bar control, and sometimes need to see the above message, and sometimes need to scroll automatically, you control
7. Click to pull out, close the page, and other forms of information display line.
DEMO by hand to achieve the ajax code to complete the form, page layout and form are also targeted through the hand-written code to complete css + div.
Because time is limited, part of the feature is not to be completed after the completion time can be further
1. Users do not click from the super-connected, but the closure of the form, this is the case, even if the closed form, but the user's information is still stored in this application, so other interface is still offline
2. If the power failure, the server-side or how to determine Li Zhang has been offline?
The realization of these problems, it is trouble!
Listed in pictures, to say the realization of the main functions and processes
1. Landing pages, automatically verify whether the name of occupied land
2. Landing, the landing interface disappeared, the main chat interface disappeared. Online users should be shown as 1 because it is intercepted before, so there is no modification.
3. To use the name Simon lv on the point of death, because the users already have.
4. For a name, you can visit, landing effect
5. More than a few users get access to land
6. No refresh message
7. San quit after the show left the chat room information, and immediately change the number of online
The above picture of the part and process part of the code below to see the content.
The request of the Home for the index.jsp
Immediately shifted to the login.jsp, then shut down itself, open the login.jsp page, change the size of opening.
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<html>
<head>
<script type="text/javascript">
function openlogin(){
window.open("login.jsp","","width=600px,height=460px");
window.opener=null;
this.close();
}
</script>
</head>
<body onload="openlogin()">
</body>
</html>
Middle window.opener = null; not so, there will be a problem, that is, self-closing index.jsp will prompt out a box, indicating whether there is a need to close this page so you can add this statement to address this问题.
login.jsp in
Part of the user to check whether there
<td > 用户名: </td> <td > <input type="text" name="name"> </td>
asynchronous request function checkUserIsExits another page
login.jsp
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<html>
<head>
<title>聊天室登录</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<script language="javascript">
function showMess(mess){
document.getElementById("mess").innerHTML="<font color='red'>"+mess+"</font>";
}
//检查用户名是否登录
function checkUserIsExits(){
var objName = document.myform.name;
if(objName.value==""){
objName.focus();
showMess("请输入用户名!");
return;
}else{
for(var i=0;i<objName.value.length;i++){
var ch = objName.value.charAt(i);
if(ch=='<' || ch =='>' || ch=='-' || ch=='/' || ch=='\\'){
objName.focus();
showMess("不能含有<,>,-等特殊字符!");
return;
}
}
}
var url = "checkUser.jsp?user="+objName.value;
sendRequest(url);
}
//定义XMLHttpRequest对象
var xmlRequest;
//创建对象
function createXMLHttpRequest(){
if(window.XMLHttpRequest) { //Mozilla 浏览器
xmlRequest = new XMLHttpRequest();
}else if (window.ActiveXObject) { // IE浏览器
try {
xmlRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
}
//发送请求函数
function sendRequest(url){
createXMLHttpRequest(); //创建对象
url=encodeURI(url);
url=encodeURI(url);
xmlRequest.open("GET",url,true);
xmlRequest.onreadystatechange = checkResponse; //响应的函数
xmlRequest.send(null);
}
//响应的函数
function checkResponse(){
if(xmlRequest.readyState==4){
if(xmlRequest.status ==200) {
//信息已经成功返回
showloginInfo();
}else{
showMess("您所请求的页面有异常!");
}
}
}
//显示函数
function showloginInfo(){
//取得 checkUser.jsp返回的XML文本
var message = xmlRequest.responseXML.getElementsByTagName("userinfo")[0].firstChild.nodeValue;
showMess(message);
//因为之前解析XML 一直出现错误 所以改用了XML文本 先显示 后取出来
if(message=="可以使用"){
showMess("<font color='blue'>可以使用该名称!</font>");
document.getElementById("sub").disabled=false; //使按钮可用
}
}
</script>
</head>
<body>
<div>
<form action="dologin.jsp" name="myform" method="post">
<table align="left" width="300">
<caption align="left"><font color="blue" size="6" face="隶书">o 蝈蝈岛聊天室 O</font></caption>
<tr >
<td >
用户名:
</td>
<td >
<input type="text" name="name">
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="登 录" disabled="true">
<input type="reset" value="重 置">
</td>
</tr>
<tr>
<td colspan="2" align="right">
<label> </label>
</td>
</tr>
<tr>
<td colspan="2">
<br>
<br>
<br>
Ajax 无刷新 简单多人聊天室DEMO,可到 <a href="http://lvp.javaeye.com" target="_blank">http://lvp.javaeye.com</a>下载
<a href="javascript:close()">退出</a></td>
</tr>
</table>
</form>
</div>
</body>
</html>
Note that there are a function login.jsp
//发送请求函数
function sendRequest(url){
createXMLHttpRequest(); //创建对象
url=encodeURI(url);
url=encodeURI(url);
xmlRequest.open("GET",url,true);
xmlRequest.onreadystatechange = checkResponse; //响应的函数
xmlRequest.send(null);
}
Appears twice, why we must add the two, I did not get to the bottom, in the transmission of Chinese encoding parameters like this before,
url = encodeURI (url);
url = encodeURI (url);
And then deal with the request to move the page to do some decoding
name = URLDecoder.decode (name, "UTF-8");
The problem does not exist in Chinese, so it does not why, but to do so, the problem is resolved.
And we must note that in the ajax in the operation of character encoding formats are UTF-8, so there is no unified on the issue.
And closely related to the login.jsp page checkUser.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.net.URLDecoder"%>
<%
//获得参数 用户名
String name = request.getParameter("user");
//name = new String(name.getBytes("ISO-8859-1"),"UTF-8");
name = URLDecoder.decode(name,"UTF-8");
//System.out.print("检查用户输入的是:"+name);
String responseText = "可以使用"; //响应字符串
//从application中取出所有已登录者的信息
ArrayList<String> list = (ArrayList<String>)application.getAttribute("users");
if(list!=null){
for(String string:list){
if(string.equals(name)){
responseText = "这个名称已经被占用!";
break;
}
}
}
//设置输出信息的格式及字符集
response.setContentType("text/xml; charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
out.print("<response>");
out.print("<userinfo>");
out.print(responseText);
out.print("</userinfo>");
out.print("</response>");
%>
Process: index.jsp to login.jsp
login.jsp in
checkUser.jsp is used to check whether the user exist.
dologin.jsp is used to handle landing.
dologin.jsp several parts of this logic:
1. To be the user into the session in
2. Add to the application of
ArrayList<String> messageList = (ArrayList<String>)application.getAttribute("messages");
if(messageList==null){
messageList = new ArrayList<String>();
}
messageList.add("\n欢迎,欢迎,大家热列欢迎!"+name+" , 进入聊天室了.....\n");
application.setAttribute("messages",messageList);
3. Shift
<script language="javascript">
//显示新窗口
function newchat(){
location.href="main.jsp";
}
</script>
</head>
<body onload="newchat()">
Chat page main.jsp
<div> <div> <marquee direction="left" scrolldelay="200"><%=name%>..欢迎来到蝈蝈岛聊天室..o(∩_∩)o.. </marquee> </div> <div> <iframe src="chat.jsp" name="chat" frameborder="1" scrolling="auto" height="350px" width="470px"> </iframe> <span>请输入内容(100字以内)! </span> <div><a href="javascript:setAuto()">自动滚动</a> <a href="javascript:clearAuto()">取消滚动</a> <a href="dolayout.jsp">退出</a></div> <div> <textarea rows="3" cols="56"></textarea> </div> <div> <input type="button" value="确定" onclick="sendMessage()"> </div> </div> <div> <iframe src="user.jsp" name="userframe" frameborder="1" scrolling="auto" height="440px" width="110px"> </iframe> </div> </div>
main.jsp component of the user.jsp and chat.jsp is mainly to build up the page.
user.jsp is to show the user page, chat.jsp chat information display is to show the page, they are inserted into the main.jsp through the iframe, but in the handling of data, I deliberately used in two ways. For almost no chat.jsp content
<%@ page language="java" pageEncoding="GBK"%>
<html>
<head>
<style type="text/css">
body{
font-size:12px;
margin:0px;
line-height:18px;
padding-left:5px;
border:2px inset #eeebbb;
}
</style>
</head>
<body >
</body>
</html> But is not the case in user.jsp
<%@ page language="java" pageEncoding="GBK"%>
<html>
<head>
<style type="text/css">
body{
font-size:12px;
margin:0px;
line-height:18px;
padding-left:5px;
}
</style>
<script language="javascript">
//用户请求数据
var xmlRequestUser;
//创建对象
function createXMLHttpRequest(){
if(window.XMLHttpRequest) { //Mozilla 浏览器
return new XMLHttpRequest();
}else if (window.ActiveXObject) { // IE浏览器
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
}
function sendGetUserRequest(){
var url = "getUser.jsp";
xmlRequestUser = createXMLHttpRequest();
xmlRequestUser.open("GET",url,true);
xmlRequestUser.onreadystatechange = getUserResponse;
xmlRequestUser.send(null);
}
function getUserResponse(){
if(xmlRequestUser.readyState==4){
if(xmlRequestUser.status ==200) {
//信息已经成功返回
showUserInfo();
}else{
showMess("您所请求的页面有异常!");
}
}
}
function showUserInfo(){
var message = xmlRequestUser.responseXML.getElementsByTagName("userinfo")[0].firstChild.nodeValue;
document.body.innerText = message;
}
//每隔10秒读取一次新用户
window.setInterval("sendGetUserRequest()",1000);
</script>
</head>
<body onload="sendGetUserRequest()">
</body>
</html>
This is the difference between the two:
1.user.jsp send their own request, to request the page getUser.jsp their own show.
Only responsible for 2.chat.jsp show that the request is completed main.jsp page, in the main.jsp page chat.jsp call asynchronous request to display the returned data.
main.jsp chat show chat.jsp call data information, it is this part of code
function showChatMessage(){
var message = xmlRequest.responseXML.getElementsByTagName("message")[0].firstChild.nodeValue;
document.frames("chat").document.body.innerText = message;
}
document.frames ( "chat"). document.body is to display the data.
//每隔三秒钟查询一次
window.setInterval("sendRequest('doinput.jsp')",1000);
var id ;
function setAuto(){
id = setInterval("document.frames('chat').document.body.scrollTop=document.frames('chat').document.body.scrollHeight",1000);
}
function clearAuto(){
clearInterval(id);
}
Behind the two methods is used to solve the chat room information on the last line of the overall display can automatically scroll the scroll bar can also be canceled automatically scroll, with this solution, many people are looking for, I hope to see here.
These are the key part of the code, the specific content or download attachments, functions are not difficult to achieve is to do one thing very carefully to the more difficult.
Source environment jdk1.6 + myeclipse, tomcat can no database code from the write pro-test, rest assured to download!
Note: IE versions, the effect of opening may be different, such as the page opened, in some flash IE browser shut down immediately and can not see the landing page, if this is the case, please see the index.jsp code page
function openlogin(){
window.open("login.jsp","","width=600px,height=460px");
//window.opener=null;//注释掉这句话就可以了 ,但是会冒出一个提示让你关闭index.jsp页面
this.close();
} 






