第一步:最基本也是最重要的,要记得配置web.xml中与reverse ajax相关的参数。
<init-param><description>是否激活反向Ajax</description><param-name>activeReverseAjaxEnabled</param-name><param-value>true</param-value></init-param> 可增加额外的两个参数:
<init-param><description>在WEB启动时是否创建范围为application的creator</description><param-name>initApplicationScopeCreatorsAtStartup</param-name><param-value>true</param-value></init-param><load-on-startup>1</load-on-startup>
第二步:编写Java的时钟代码:
package learn.dwr.reverse;import java.util.Date;import java.util.concurrent.ScheduledThreadPoolExecutor;import java.util.concurrent.TimeUnit;import org.directwebremoting.Browser;import org.directwebremoting.ServerContextFactory;import org.directwebremoting.ui.dwr.Util;/** * title: 时钟 * * @author Administrator * @时间 2009-11-21:下午07:11:56 */public class MyClock implements Runnable {// 这个active必需用static,使用transient标识是无法使用哦。protected static boolean active = false;public MyClock() {ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);executor.scheduleAtFixedRate(this, 1, 1, TimeUnit.SECONDS);}@Overridepublic void run() {if (active) {setClockDisplay((new Date()).toString());}}public synchronized void toggle() {active = !active;if (active) {setClockDisplay("Started");} else {setClockDisplay("Stopped");}}public void setClockDisplay(final String output) {String page = ServerContextFactory.get().getContextPath()+ "/reverseajax/clock.html";System.out.println(page + " " + output);Browser.withPage(page, new Runnable() {public void run() {Util.setValue("clockDisplay", output);}});}}
第三步:把MyClock类配置到dwr.xml中内容如下:
<create creator="new"><param name="class" value="learn.dwr.reverse.MyClock" /></create> 注意:creator="new",每当我们点击“Start/Stop”按钮时,它会自动生成一个新的Clock对象,此时我们应该把设置范围,scope="application",用application范围时,它就不会再每次点击“Start/Stop”时创建新的Clock对象,因为Clock对象,只有应用程序启动时创建一个Clock对象。
第四步:创建/reverseajax/clock.html语言件,并编写HTML代码,其内容如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Reverse ajax 时钟案例</title><script type='text/javascript' src='/learnajax/dwr/interface/MyClock.js'></script><script type='text/javascript' src='/learnajax/dwr/engine.js'></script><script type='text/javascript' src='/learnajax/dwr/util.js'></script><script type="text/javascript">window.onload = function (){dwr.engine.setActiveReverseAjax(true);}</script></head><body><input type="button" value="Start/Stop" /><h2 id="clockDisplay"></h2></body></html> DWR Rerverse AJAX 的高级应用。
|