实现网页方式的即时消息通信
页面jsp
<%@ page language="java" import="com.trilink.xf.tools.Common" pageEncoding="UTF-8"%>
<%@ include file="/common/taglibs.jsp"%>
<!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=utf-8" />
<title>即时通讯</title>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script>
window.setInterval("connection();",3000);
function connection(){
//var link = "${ctx}/ajaxConnection/ajaxAction.json?rd=" + new Date().valueOf();//加随机参数防止缓存
$.ajax({
url:"${path}/sysmanage_InstantMessage_queryMessage2_n.action",
type:"POST",
dataType:"json",
context:this,
success : function(text) {
if(text == null){
return ;
}
var t = eval(text);
for(var i=0;i<t.sz.length;i++){
var str=$("#message").append("<tr><td>"+t.sz[i]+"</td></tr>");
}
$.ajax({
url:"${path}/sysmanage_InstantMessage_updateMessage_n.action",
type:"POST",
data:{messageId:t.id},
dataType:"json",
context:this,
success : function(text){
}
});
}
});
}
</script>
</head>
<body>
<table id="message" >
<s:iterator value="list" var="li">
<tr >
<td><s:property value="#li.message"/></td>
</tr>
</s:iterator>
</table>
</body>
</html>
后台代码首先是 页面列表显示数据,然后跳jsp。
ajax向action发送请求
public void queryMessage2(){
try {
PrintWriter pw =ServletActionContext.getResponse().getWriter();
list=iInstantMessageService.queryMessage2(1);
if(list.size()==0){
return;
}else{
StringBuilder sb =new StringBuilder("{\"sz\":[");
String sb2 = "\"id\":\"";
for(Message message:list){
String str=message.getMessage();
int id=message.getId();
sb2+=id+",";
sb.append("\""+str+"\",");
}
if(list.size()!=0){
sb2 = sb2.substring(0, sb2.length()-1);
}
sb2+="\"";
String str2=sb.toString();
if(sb.length()!=0){
str2 =sb.substring(0, sb.length()-1);
}
str2+="],"+sb2+"}";
System.out.println(str2);
pw.print(str2);
}
} catch (IOException e) {
e.printStackTrace();
}
}