並回傳一個 JavaBean 的物件,最後呈現在網頁上
這也是一個典型的 Java 與 Javascript 物件之件的轉換,以下來看看範例吧
首先環境就不多說了,可以看,上一篇文章
一開始我們先定義一個 JavaBean
package org.bean; public class PersonBean { private String name; private String dollar; public PersonBean(){} // getter&setter 省略 }接著同樣的要定義一個遠端的服務,透過Javascript 呼叫 它會建立一個 PersonBean 並將這個物件回傳回去
package org.service; import org.bean.PersonBean; public class PersonService{ public PersonBean getPerson(){ PersonBean personbean = new PersonBean(); personbean.setDollar("1000"); personbean.setName("Allen"); return personbean; } }最後要定義 dwr.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting
2.0//EN" "http://getahead.org/dwr/dwr20.dtd">
<dwr>
<allow>
<create creator="new"
javascript="PersonService">
<param name="class"
value="org.service.PersonService" />
</create>
<convert converter="bean"
match="org.bean.PersonBean" javascript="Person"/>
</allow>
</dwr>
convert 是告訴 DWR 運用 bean 的方式轉換 PersonBean 這個物件
最後就來看看前端網頁的程式
<%@ page
language="java" contentType="text/html;
charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>Ch1</title>
<script type='text/javascript'
src='dwr/interface/PersonService.js'></script>
<script type='text/javascript'
src='dwr/engine.js'></script>
<script type='text/javascript'
src='dwr/util.js'></script>
<script type="text/javascript">
function hello(){
Hello.getPerson(callback);
}
function callback(obj){ //重點 !! DWR會轉換Java物件成為一個Javascript 物件
DWRUtil.setValue("Name",obj.name);
DWRUtil.setValue("Dollar",obj.dollar);
}
</script>
</head>
<body>
<input id="user"
type="text" />
<input id="button"
type='button' value='Button1'
onclick='hello();' />
<br/>
Name: <span id="Name"></span> <br/>
Dollar: <span
id="Dollar"></span><br/>
</body>
</html>
沒有留言:
張貼留言