`

DWR的 Reverse Ajax!

    博客分类:
  • DWR
阅读更多

下面内容出自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="开始" onclick="Clock.toggle();" />
		<div id="clockDisplay">这里用来显示后台服务器推送的内容(即Count的值)</div>
	</body>
</html>

 
第三步:Web页面内容
补充:这里的文件名是index.html

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics