logo
BLOGARCHIVEGITHUB
DWR简单入门
2015年5月16日
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的内容为:
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">
在/WEB-INF目录下新建dwr.xml,内容为:
"-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN"
"http://getahead.org/dwr/dwr30.dtd">
启动Tomcat,访问http://localhost:8088/DwrEx/dwr/,可以看到dwr.xml中配置的java.util.Date的所有方法;由于web.xml将参数debug初始化为true,可以在页面动态调试这些方法。
creator元素
...
creator属性设置为new,即使用Java类的new操作获得实例;
javascript属性指定从JS访问对象时使用的名称(避免使用JS关键字);
scope属性的默认值为page;
include和exclude属性分别用于指定允许使用和限制使用的方法。
...
将java.util.Date公开给Javascript,使用Blah来访问对象,在JavaScript中调用Blah.toString(reply)时, 使用默认构造器实例化java.util.Date,调用toString()方法返回数据到JavaScript。
convert元素
convertor属性设置为bean,将JavaBean对象(Person)转化为JavaScript对象;
include/exclude同样适用于convert,参数值为变量名而不是方法名。
public class Remoted {
public void addToFriends(Person p) {
// ...
}
}
public class Person {
public void setName(String name) { ... }
public void setAge(int age) { ... }
// ...
}
如果Remoted类已经配置为create,可以在JS中调用,
var p = { name:"Fred", age:21 };
Remoted.addToFriends(p);
参考资料
Getting Started with DWR
The Creators
Bean and Object Converters
上一篇下一篇
© 2014 - 2017 Jemoii, powered by Hexo and hexo-theme-apollo.