Direct Web Remoting

DWR is a Java library that enables Java on the server and JavaScript in a browser to interact and call each other as simply as possible.

新建DWR工程

新建工程DwrEx,将下载的dwr.jar和依赖包commons-logging-1.2.jar放在/WEB-INF/lib目录下,

web.xml的内容为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<web-app xmlns = "http://java.sun.com/xml/ns/j2ee"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version = "2.4">
<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>
</web-app>

/WEB-INF目录下新建dwr.xml,内容为:

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE dwr PUBLIC
"-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN"
"http://getahead.org/dwr/dwr30.dtd">
<dwr>
<allow>
<create creator="new" javascript="JDate">
<param name="class" value="java.util.Date"/>
</create>
</allow>
</dwr>

启动Tomcat,访问http://localhost:8088/DwrEx/dwr/,可以看到dwr.xml中配置的java.util.Date的所有方法;由于web.xml将参数debug初始化为true,可以在页面动态调试这些方法。

creator元素

<create ...>用于将服务端的Java类公开给客户端,一般结构为,

1
2
3
4
5
6
7
8
<allow>
<create creator="..." javascript="..." scope="...">
<param name="..." value="..."/>
<exclude method="..."/>
<include method="..."/>
</create>
...
</allow>
  • creator属性设置为new,即使用Java类的new操作获得实例;
  • javascript属性指定从JS访问对象时使用的名称(避免使用JS关键字);
  • scope属性的默认值为page
  • includeexclude属性分别用于指定允许使用和限制使用的方法。
1
2
3
4
5
6
<allow>
<create creator="new" javascript="Blah">
<param name="class" value="java.util.Date"/>
</create>
...
</allow>

java.util.Date公开给Javascript,使用Blah来访问对象,在JavaScript中调用Blah.toString(reply)时, 使用默认构造器实例化java.util.Date,调用toString()方法返回数据到JavaScript。

convert元素

<convert ...>用于在客户端和服务端之间序列化数据,将Java返回类型序列化为JS对象,以及将被传递的JS对象序列化为合适的Java对象

1
2
3
<convert converter="bean" match="com.example.Person">
<param name="exclude" value="property1, property2"/>
</convert>
  • convertor属性设置为bean,将JavaBean对象(Person)转化为JavaScript对象;
  • include/exclude同样适用于convert,参数值为变量名而不是方法名。
1
2
3
4
5
6
7
8
9
10
11
public class Remoted {
public void addToFriends(Person p) {
// ...
}
}
public class Person {
public void setName(String name) { ... }
public void setAge(int age) { ... }
// ...
}

如果Remoted类已经配置为create,可以在JS中调用,

1
2
var p = { name:"Fred", age:21 };
Remoted.addToFriends(p);
参考资料

Getting Started with DWR

The Creators

Bean and Object Converters