DWR第四篇之对象传参

时间:2024-12-06 12:33:26

1. 本示例在第一篇架构基础上添加代码

2. 首先,在dwr.xml文件里添加对象转换器

DWR第四篇之对象传参

3. 编写Person实体类

 package com.skyer.vo;

 import java.util.Arrays;

 public class Person {
private String name;
private int age;
private String[] hobby; public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
} @Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", hobby=" + Arrays.toString(hobby) + "]";
}
}

4. 在核心控制器(CoreServlet.java)里添加如下方法:

 public Person printPerson(Person person) {
System.out.println(person);
return person;
}

5. 编写测试的jsp页面:

 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>dwr</title>
<script type='text/javascript' src='dwr/engine.js'></script>
<script type='text/javascript' src='dwr/util.js'></script>
<script type='text/javascript' src='dwr/interface/CoreServlet.js'></script>
</head>
<body>
<div style="margin-top: 20px" align="center">
<button onclick="printPerson();">点击</button>
</div>
</body>
<script type="text/javascript">
function printPerson() {
var person = {
name: "skyer",
age: 18,
hobby: [ "爱好1", "爱好2", "爱好3" ]
}; CoreServlet.printPerson(person, function(data) {
alert(data.name + ":" + data.age + ":" + data.hobby);
});
}
</script>
</html>

6. 测试