DWR Reverse Ajax

后台java

import java.util.Collection;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ServerContext;
import org.directwebremoting.ServerContextFactory;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

public void newMessage(String message) {
WebContext wctx = WebContextFactory.get();
ScriptBuffer script = new ScriptBuffer();
script.appendScript("receiveMessages(").appendData(message).appendScript(");");
ServerContext sctx = ServerContextFactory.get(wctx.getServletContext());
Collection pages = sctx.getScriptSessionsByPage("/YGO/room.jsp");
for (Object session : pages) {
((ScriptSession)session).addScript(script);
}
}


web.xml


<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>
org.directwebremoting.servlet.DwrServlet
</servlet-class>
<init-param>
<param-name>activeReverseAjaxEnabled</param-name>
<param-value>true</param-value>
</init-param>
<!--
<init-param>
<param-name>initApplicationScopeCreatorsAtStartup</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
-->
</servlet>

第一个 servlet init-param,activeReverseAjaxEnabled 将激活轮询和 Comet 功能。(省略:第二个 initApplicationScopeCreatorsAtStartup 通知 DWR 在应用程序启动时初始化 ReverseAjaxTracker。这将在对 bean 生成第一个请求时改写延迟初始化(lazy initialization)的常规行为 —— 在本例中这是必须的,因为客户机不会主动对 ReverseAjaxTracker 调用方法。)

最后,我需要实现调用自 DWR 的客户端 JavaScript 函数。将向回调函数 —— updateCoordinate() —— 传递 GpsCoord Java bean 的 JSON 表示,由 DWR 的 BeanConverter 自动序列化。该函数将从坐标中提取 longitude 和 latitude 字段,并通过调用 Document Object Model (DOM) 将它们附加到列表中。清单 13 展示了这一过程,以及页面的 onload 函数。onload 包含对 dwr.engine.setActiveReverseAjax(true) 的调用,将通知 DWR 打开与服务器的持久连接并等待回调。


前台jsp


window.onload = function() {
dwr.engine.setActiveReverseAjax(true);
}

function receiveMessages(message) {
document.getElementById('chatcontent').innerHTML = document.getElementById('chatcontent').innerHTML + message + "<br/>";
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值