DWR例子1 --调用后台无参方法
Step 1: Download
从网站下载 DWR: http://getahead.ltd.uk/dwr/download
导入jar
?dwr.jar
commons-logging-1.0.4.jar(dwr 3.0需要这个包)
?
Step 2: web.xml修改 web.xml, 新增 DwrServlet<servlet> <display-name>DWR Servlet</display-name> <servlet-name>dwr-invoker</servlet-name> <servlet-class> org.directwebremoting.servlet.DwrServlet </servlet-class> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param></servlet><servlet-mapping> <servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern></servlet-mapping>?Step 3: dwr.xml
将远端 Java 物件注册到 dwr.xml
参考:dwr.jar/org.directwebremoting/dwr.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN" "http://getahead.org/dwr/dwr30.dtd"><dwr><allow><create creator="new" javascript="helloWorld"><param name="class" value="com.wepull.dwr.HelloWorld"></param></create></allow></dwr>
?
?Step 3? 测试测试 DWR
将代码放入应用服务器(比如Tomcat),启动。
然后在地址栏输入:
http://localhost:8080/工程名称/dwr
?
?
?Step?4 前台页面<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>testDWR.html</title><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="this is my page"><meta http-equiv="content-type" content="text/html; charset=UTF-8"><!--<link rel="stylesheet" type="text/css" href="./styles.css">--><script type="text/javascript"src="/1102_DWR/dwr/interface/helloWorld.js"></script><script type='text/javascript' src='/1102_DWR/dwr/engine.js'></script><script type='text/javascript' src='/1102_DWR/dwr/util.js'></script><script type="text/javascript">function sayHello(){//helloWorld 为helloWorld.js 中的helloWorld//callBack 是个回调函数helloWorld.sayHello(callBack);}//text为服务器传到前台的数据function callBack(text){alert(text);//var obj = document.getElementById("sp1");//DWR 中可以$("sp1") 来获取对象 var obj = $("sp1"); //sp1是id名obj.innerHTML = text;}</script></head><body><input type="button" value="调用后台sayHello()方法" onclick="sayHello()"><span id="sp1"></span></body></html>
?
?
附:后台代码
package com.wepull.dwr;public class HelloWorld {public String sayHello(){System.out.println("执行了 sayHello()方法");return "hello world";}}
?
?
?