`
chenqian
  • 浏览: 77900 次
  • 性别: Icon_minigender_1
  • 来自: 湘潭
社区版块
存档分类
最新评论

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/>";
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics