首先我们给出两个类:
Group.java
package org.konghao.dwr.model;
public class Group {
private int id ;
private String name ;
public Group(int id, String name) {
super();
this.id = id;
this.name = name;
}
public Group() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return "Group [id=" + id + ", name=" + name + "]";
}
}
User.java
package org.konghao.dwr.model;
public class User {
private int id ;
private String username ;
private Group group;
public User() {
super();
}
public User(int id, String username, Group group) {
super();
this.id = id;
this.username = username;
this.group = group;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", group=" + group
+ "]";
}
}
MyException.java
package org.konghao.dwr.model;
public class MyException extends RuntimeException {
public MyException() {}
public MyException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public MyException(String message, Throwable cause) {
super(message, cause);
}
public MyException(String message) {
super(message);
}
public MyException(Throwable cause) {
super(cause);
}
}
下面我们在类MyDwr.java
中添加一些方法:
package org.konghao.dwr.model;
import java.util.ArrayList;
import java.util.List;
public class MyDwr {
public String hello(String world){
System.out.println("hello " + world);
return "hello" + world;
}
public User load(){
User user = new User(1,"张三", new Group(1, "财务处"));
return user;
}
public List<User> list(){
List<User> users = new ArrayList<User>();
users.add(new User(1,"张三", new Group(1, "财务处")));
users.add(new User(2,"李四", new Group(2, "科技处")));
users.add(new User(3,"王五", new Group(3, "宣传部")));
return users;
}
public void add(User user){
System.out.println(user);
}
public void deleteUser(){
throw new MyException("在删除用户出现异常");
}
}
下面我们在使用js
代码来直接访问这个类中的相关方法:
dwr02.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>dwr02.jsp</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/dwr/engine.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/dwr/interface/MyDwr.js"></script>
<script type="text/javascript">
//这里调用load方法,此方法没有参数,这里我们只是给出一个回调函数
MyDwr.load(loadUser);
function loadUser(user){
alert(user.id + "," + user.username + "," + user.group.name);
}
</script>
</head>
<body></body>
</html>
但是我们在访问此jsp
的时候发现user
的相关值访问不到,这是因为对于javabean
类型的数据,我们需要添加相关的转换器。在类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">
<param name="class" value="org.konghao.dwr.model.MyDwr" />
</create>
<convert converter="bean" match="org.konghao.dwr.model.User"/>
<convert converter="bean" match="org.konghao.dwr.model.Group"/>
<convert converter="exception" match="java.lang.Exception" />
</allow>
</dwr>
在后面还需要用到异常,所以这里我们将异常类的转换器也添加进去。此时测试结果是:
从这里我们可以看到我们可以直接访问到
java
类的相关属性。这是访问javabean
的相关属性,还可以访问相关的java
集合。dwr03.jsp
<script type="text/javascript">
MyDwr.list(listUser);
function listUser(users){
for(var i = 0; i <users.length; i++){
alert(users[i].id + "," + users[i].username + "," + users[i].group.name);
}
}
</script>
我们还可以使用json
串来进行添加:
dwr04.jsp
<script type="text/javascript">
var user = {id:1, username:"李四",group:{id:2, name:"网络中心"}};
MyDwr.add(user);
</script>
当然我们还可以取得相关的异常消息:
dwr05.jsp
<script type="text/javascript">
MyDwr.deleteUser({
callback: deleteUser,
errorHandler: function(msg, exception){
alert(msg);
}
});
function deleteUser(data){};
</script>
这里我们在测试的时候会发现打印出相关异常消息。
对于异常处理,dwr
给出了其他一些属性,首先我们改造上面的jsp
:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>dwr01.jsp</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/dwr/engine.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/dwr/interface/MyDwr.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/dwr/util.js"></script>
<script type="text/javascript">
MyDwr.deleteUser({
callback: deleteUser,
errorHandler: function(msg, exception){
alert(msg);
alert(exception.javaClassName);
alert(dwr.util.toDescriptiveString(exception, 2));
}
});
function deleteUser(data){};
</script>
</head>
<body></body>
</html>
说明:这里我们使用了dwr
的一个工具js
(util.js
),同时需要在dwr.xml
中配置:
<convert converter="bean" match="java.lang.StackTraceElement" />
然后进行测试,会弹出相关的信息,最后弹出的是异常的默认属性:
相关的使用可以查看文档。下面看一下工具
util.js
的相关方法的使用:先在
MyDwr.java
中添加一个方法:
public int add(int a, int b){
return a + b;
}
dwr06.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>dwr06.jsp</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/dwr/engine.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/dwr/interface/MyDwr.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/dwr/util.js"></script>
<script type="text/javascript">
function calAdd(){
var a = dwr.util.getValue("a");//取得id为a的元素的值
var b = dwr.util.getValue("b");
MyDwr.add(parseInt(a), parseInt(b), function(data){
alert(data);
});
}
function addAddress(){
var a = dwr.util.getValue("addressName");//取得id为addressName的值
/* var data = [{id:1, name:'北京'},{id:2, name:'天津'}]; */
var data = [{id:a, name:a}];
dwr.util.addOptions("address", data, "id", "name");//向id为address的元素添加值
}
function initAddress(){
dwr.util.removeAllOptions();
var data = [{id:1, name:'北京'},{id:2, name:'天津'},{id:3, name:'上海'}];
dwr.util.addOptions("address", data, "id", "name");
}
function initUser(){
MyDwr.list(function(data){
dwr.util.addRows("user", data, cellFuncs, {escapeHtml: false});
});
}
var cellFuncs = [
function(data){return data.id;},
function(data){return data.username;},
function(data){return data.group.name;}
];
</script>
</head>
<body>
<input type="text" id="a">+
<input type="text" id="b">
<input type="button" value="获取" onclick="calAdd()">
<br>
<select id="address"></select>
<input type="button" value="初始化地址" onclick="initAddress()">
<input type="text" id="addressName">
<input type="button" value="添加" onclick="addAddress()">
<table width="600px" border="1px">
<thead>
<tr>
<td>id</td>
<td>username</td>
<td>groupName</td>
</tr>
</thead>
<tbody id="user"></tbody>
</table>
<input type="button" value="初始化用户" onclick="initUser()">
</body>
</html>
在测试的时候,方法calAdd
可以达到将两个输入值相加的功能。这里使用getValue
取得相关元素的值。点击“初始化地址”时可以将相关的值添加到select
中,同时也可以点击“添加”向select
中添加值。当然在后面我们还可以像table
中添加值。
下面我们看文件上传:
首先我们还是在MyDwr.java
中添加一个方法:
public String upload(InputStream is, String filename) throws IOException{
String fn = FilenameUtils.getName(filename);//获取文件名称
FileUtils.copyInputStreamToFile(is, new File("d:/webservice/" + fn));
return fn;
}
dwr07.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>dwr07.jsp</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/dwr/engine.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/dwr/interface/MyDwr.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/dwr/util.js"></script>
<script type="text/javascript">
function upload(){
var file = dwr.util.getValue("myfile");
alert(file.value);
alert(file);
MyDwr.upload(file, file.value, function(data){
alert(data);
});
}
</script>
</head>
<body>
<input type="file" id="myfile">
<input type="button" value="上传文件" onclick="upload()">
</body>
</html>
这样就实现了文件上传。不仅如此,我们还可以获得HttpServletRequest
等对象,这里我们先对方法upload
进行改造:
public String upload(InputStream is, String filename) throws IOException{
//WebContext可以获取HttpServletRequest对象
WebContext wc = WebContextFactory.get();
HttpServletRequest request = wc.getHttpServletRequest();
String realPath = request.getSession().getServletContext().getRealPath("upload");
String fn = FilenameUtils.getName(filename);//获取文件名称\
String filePath = realPath + "/" + fn;
FileUtils.copyInputStreamToFile(is, new File(filePath));
return filePath;
}
还是使用dwr07.jsp
进行测试,我们会发现文件被上传到本工程中了。