2012年2月11日 星期六

【DWR】集合物件與JavaBean


最後的範例綜合前面的所介紹的,底下程式提供一個遠端服務,

能夠取得所有書籍(BookBean),並放到Java的List集合內以回傳給前端網頁的Javascript

先來看一下BookBean.java的內容

package org.bean;

/**
 * @author allen
 *
 */
public class BookBean 
{
 private String title;
 private int price;
 
 public BookBean(){}

 public String getTitle() {
  return title;
 }

 public void setTitle(String title) {
  this.title = title;
 }

 public int getPrice() {
  return price;
 }

 public void setPrice(int price) {
  this.price = price;
 }
}

接著提供一個遠端服務 BookService.java

package org.service;
import java.util.ArrayList;
import java.util.List;
import org.bean.BookBean;
/**
 * @author allen
 *
 */
public class BookService 
{
    //假資料
    private String[] title = new String[]{"Cook Java", "Java Learning", "Spring tech", "SSH tech", "UML learning"};
    private int[] price = new int[]{600, 500, 400, 700, 900};
    private List books;
 
    public BookService(){
        BookBean book;
        books = new ArrayList();
        for(int i=0;i<5;i++){
            book = new BookBean();
            book.setTitle(title[i]);
            book.setPrice(price[i]);
            books.add(book);
        }
    }
 
    public List getAllBooks(){
        return this.books;
    }
}


最後要在dwr.xml中定義BookService 以及BookBean


<dwr>
  <allow>
    <create creator="new" javascript="BookService">
      <param name="class" value="org.service.BookService" />
    </create>
    <convert converter="bean" match="org.bean.BookBean" javascript="Book"/>
  </allow>
</dwr>


最後來看看網頁程式如何呈現此結果


<head>
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
src='dwr/interface/BookService.js' />
     <script type='text/javascript' src='dwr/engine.js'/>
     <script type='text/javascript' src='dwr/util.js'/>
     <script type="text/javascript">
    function getBooks()
    {
          BookService.getAllBooks(showBooks);
    }
    function showBooks(books)
    {
          var tableHtml = "";
        for (var data in books) {
         tableHtml = tableHtml + "書名 : " + books[data].title +
                架格 : " + books[data].price + "    \n";
        }
        DWRUtil.setValue("show", tableHtml);
    }
    </script>
</head>
<body>
取得所有書籍:<input type="button" value="取得所有書籍" onclick="getBooks();"/><br/>
<div id="show">
</div>
</body>

沒有留言:

張貼留言