日期:2014-05-16  浏览次数:20708 次

反向ajax小例子
所谓反向ajax是指服务器端通过一系列API来控制浏览器端元素,实际上反向控制只是一种形象的说法,能够操作浏览器页面元素的只能是客户端脚本,只是在服务器端加入一系列操作客户端元素的API这样问题就解决了
既然要实现反向ajax,首先要设置反向ajax的参数,在web.xml中设置参数
 <init-param>
         <param-name>activeReverseAjaxEnabled</param-name>
         <param-value>true</param-value>
 </init-param>

客户端页面在加载的时候需要指定
<body onload="dwr.engine.setActiveReverseAjax(true);">
完整代码如下,客户端页面
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>利用反向ajax实现页面聊天</title>

		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
		<meta http-equiv="description" content="this is my page">
		<meta http-equiv="content-type" content="text/html; charset=UTF-8">

		<script type="text/javascript" src="dwr/interface/DWRHelper.js"></script>
		<script type="text/javascript" src="dwr/engine.js"></script>
		<script type="text/javascript" src="dwr/util.js"></script>
		<script type="text/javascript">
		function sendMessage(){
			DWRHelper.addMessage(dwr.util.getValue("myText"));
		}
	</script>

	</head>

	<body onload="dwr.engine.setActiveReverseAjax(true);">
	
		<input type="text" id="myText" />
		<input type="button" value="发送" onclick="sendMessage()" />
		
		<div style="width: 300px; height: 300px; border: 1px solid blue">
			<ul id="chatlog"></ul>
		</div>
	</body>
</html>

src="dwr/interface/DWRHelper.js"中的DWRHelper必须与DWRHelper.addMessage(...)名称必须相一致

服务器端代码如下

package com.lamp;

import java.util.Collection;
import java.util.LinkedList;

import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.proxy.dwr.Util;

public class DWRHelper {
	LinkedList<Message> messages = new LinkedList<Message>();
	public void addMessage(String text) {
		
		if (text.trim().length() > 0 || text != null) {
			messages.addFirst(new Message(text));
			while (messages.size() > 10) {
				messages.removeLast();
			}
		}
		System.out.println(text);
		WebContext context = WebContextFactory.get(); // 获得容器上下问

		String currentPage = context.getCurrentPage(); // 获得当前页面

		Util util = new Util(context.getScriptSession());

		util.setValue("myText", ""); // 清空当前编辑框

		Collection sessions = context.getScriptSessionsByPage(currentPage); // 打开当前页面的所有会话集合

		Util utilAll = new Util(sessions);

		utilAll.removeAllOptions("chatlog");		//清空原来列表的内容

		utilAll.addOptions("chatlog", messages, "text");	//将消息显示在列表中

	}

}


bean类Message如下

package com.lamp;

public class Message {
	private String text;

	public Message() {
	}
	
	public Message(String text) {
		this.text = text;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

}


dwr.xml需设置为
<create javascript="DWRHelper" creator="new"
			scope="application">
			<param name="class" value="com.lamp.DWRHelper"></param>
		</create>
		<convert match="com.lamp.Message" converter="bean">
			<param name="include" value="id,text"></param>
		</convert>