编辑配置web.xml文件加入以下配置:
- <servlet>
- <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>
<servlet> <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>
l 编写JSP测试页面
<1 引用dwr自动生成的js,dwr/interface/service.js,注意js名字要和dwr.xml配置的一样
<2 js里的service.sayHello和java类的那个有一点区别,多了个参数,用来callback返回的
数据
- <script type="text/javascript" src="<%=path%>/dwr/util.js"></script>
- <script type="text/javascript" src="<%=path%>/dwr/engine.js"></script>
- <script type='text/javascript' src='<%=path%>/dwr/interface/Demo.js'></script>
<script type="text/javascript" src="<%=path%>/dwr/util.js"></script>
<script type="text/javascript" src="<%=path%>/dwr/engine.js"></script>
<script type='text/javascript' src='<%=path%>/dwr/interface/Demo.js'></script>
- <script type="text/javascript">
- function update() {
- var name = dwr.util.getValue("demoName");
- Demo.sayHello(name,function(data){
<script type="text/javascript">
function update() {
var name = dwr.util.getValue("demoName");
Demo.sayHello(name,function(data){
- dwr.util.setValue("demoReply",data);
- });
- }
- </script>
- <body>
- <h2>示例</h2>
- <p>
- Name:<input type="text" id="demoName" />
- <input value="Send" type="button" onclick="update()" />
- <br />
- Reply:span id="demoReply"></span>
- </p>
- </body>
dwr.util.setValue("demoReply",data);
});
}
</script>
<body>
<h2>示例</h2>
<p>
Name:<input type="text" id="demoName" />
<input value="Send" type="button" οnclick="update()" />
<br />
Reply:span id="demoReply"></span>
</p>
</body>
<参考示例代码>
编写serivce类
- package com.dwrdemo;
- /**
- * @deprecated:
- * @author: vince
- * @version 1.0
- * @email finally_m@yahoo.cn
- */
- public class Demo{
- public String sayHello(String name) {
- return "Hello, " + name;
- }
- }
package com.dwrdemo;
/**
* @deprecated:
* @author: vince
* @version 1.0
* @email finally_m@yahoo.cn
*/
public class Demo{
public String sayHello(String name) {
return "Hello, " + name;
}
}
l 在web.xml的同一目录下,创建dwr.xml,并且将要被调用的java类写入其中
- <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://www.getahead.ltd.uk/dwr/dwr20.dtd">
- <dwr>
- <allow>
- <create creator="new" javascript="Demo">
- <param name="class" value="com.dwrdemo.Demo" />
- </create>
- </allow>
- </dwr>