六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 33|回复: 0

DWR的 Reverse Ajax!

[复制链接]

升级  60%

36

主题

36

主题

36

主题

秀才

Rank: 2

积分
140
 楼主| 发表于 2013-1-22 22:47:03 | 显示全部楼层 |阅读模式
下面内容出自0:javaeye的 hellostory 大虾。十分感谢他帮我解决了这个问题!
 
说明:可以将以下count值改变为表格内容

以下代码演示内容:
    后台服务不停地累加count值,同时将count值推送到前台页面(index.html)中(表现为前台页面count值不停地累加显示)

第一步:创建后台推送服务
 

 
import java.util.Timer;import java.util.TimerTask;import org.directwebremoting.Browser;import org.directwebremoting.ServerContextFactory;import org.directwebremoting.ui.dwr.Util;public class Clock {private long count = 0;//计数器,web页面用来显示public Clock() {// 创建一个定时任务,每隔10秒count自动加一Timer t = new Timer();t.schedule(new TimerTask() {public void run() {count++;}}, 0,10);}// 通过无限循环调用setClockDisplay()刷新Web页面的数字内容public synchronized void toggle() {while (true) {setClockDisplay(count+"");//休眠一秒try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}// 刷新index.html页面中<div id='clockDisplay'/>的内容,// 即显示count的数值public void setClockDisplay(final String output) {String page = ServerContextFactory.get().getContextPath()+ "/index.html";Browser.withPage(page, new Runnable() {public void run() {Util.setValue("clockDisplay", output);}});}} 
第二步:配置dwr.xml
<!DOCTYPE dwr PUBLIC    "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN"    "http://getahead.org/dwr/dwr20.dtd"><dwr>  <allow>    <create creator="new" javascript="Clock">      <param name="class" value="Clock"/>    </create>  </allow></dwr> 第三步:Web页面内容
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>Comet测试</title><meta http-equiv="content-type" content="text/html; charset=UTF-8"><script type="text/javascript" src="dwr/interface/Clock.js"></script><script type='text/javascript' src='dwr/engine.js'></script><script type='text/javascript' src='dwr/util.js'></script><script type="text/javascript">dwr.engine.setActiveReverseAjax(true);//开启ajax反转功能</script></head><body><input type="button" value="开始"  /><div id="clockDisplay">这里用来显示后台服务器推送的内容(即Count的值)</div></body></html> 
第三步:Web页面内容
补充:这里的文件名是index.html
 
 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表