总结DWR的ReverseAjax应用

DWR提供了ReverseAjax技能,也就是服务器端主动更新客户端,或者说推模式。实际是长连接或轮循方式实现。各页面有对应的ScriptSession,用来存放需要发送到页面的内容。需要推到页面时,设置ScriptSession即可。

实际应用上有些不方便的地方(rq2_79提出此问题在 http://www.iteye.com/post/387395),常规情况只能在DWR公开的方法(dwr.xml内include的方法)内实现。由于WebContext需要DwrServlet创建,所以在DWR公开方法之外的地方WebContextFactory.get();会返回null,无法继续使用。

DWR使用了准Ioc方式统一创建各功能模块,在DwrServlet中的Container承担此责任,默认为DefaultContainer。在不能得到WebContext的情况下,能直接得到ScriptSessionManager也可以取得最终的ScriptSession。直接new DefaultScriptSessionManager不能得到已经注册的页面,必须通过Container取得。现在问题变成如何取得Container了。DwrServlet有一个public 的getContainer,简单粗暴的改成 staitc,同样,container 也static,一切ok。
在需要推到页面的地方,随便调用吧。
java 代码
 
  1. Container container = DwrServlet.getContainer();  
  2. ScriptSessionManager ssm = (ScriptSessionManager) container.getBean(ScriptSessionManager.class.getName());  
  3. Collection<ScriptSession> sessions = ssm.getScriptSessionsByPage("/dwrt/");  
  4. Util utilAll = new Util(sessions);  
  5. ScriptBuffer s = new ScriptBuffer();  
  6. s.appendScript("alert(");  
  7. s.appendData("something funny here!");  
  8. s.appendScript(");");  
  9. utilAll.addScript(s);  

你可能感兴趣的:(应用服务器,浏览器,DWR,IOC,Comet)