顯示具有 sMash 標籤的文章。 顯示所有文章
顯示具有 sMash 標籤的文章。 顯示所有文章

2010年12月20日 星期一

sMash--使用ZRM

ZRM為定義在 app/models 下的data model,提供了簡單的HTTP RESTful的實作。只要在app/models目錄下,使用JSON定義 entity model,然後在app/resources/ 目錄下,建立一行groovy程式,即可對該model進行CRUD的RESTful操作。實際順序如下

  1. 在應用程式根目錄的 app/models/ 子目錄,建立一個json檔來描述要model的entity的schema,如下
    {
        "fields":{
            "firstname":{"type":"string"},
            "birthday":{"type":"date"}
        }
    }
  2. 在 config/ivy.xml中,加下這一行,以include zero resource的library
    <dependency name="zero.resource" org="zero" rev="[1.1.0.2, 2.0.0.0["/>   
  3. 在config/zero.config,加入下列內容。用/config/resource/dbKey設定ZRM要用那個db config,然後用/config/db/xxx 設定該db config的內容
    /config/db/test = {
        "class" : "com.ibm.db2.jcc.DB2SimpleDataSource",
        "driverType" : 4,
        "serverName" : "localhost",
        "portNumber" : 50000,
        "databaseName" : "JPATEST",
        "user" : "db2admin",
        "password" : "password"
    }
    /config/resource/dbKey = "test"
  4. 複製database driver檔案到 lib/目錄下,並 resolve
  5. 關閉eclipse,開啟CMD程式,變更路徑到應用程式根目錄,執行命令:(一定要關閉eclipse,否則無法執行)
    zero  model  sync
  6. 完成後,可發現資料庫已建立一個新的表格: persons
  7. 打開browser,執行 POST   http://server:port/resources/persons     並將一筆person的資料以JSON格式傳入,執行完成後,即可發現新建的persons 表格已建立該筆資料
    {
         “firstname”:”Janie”,
           “birthday”:”1973-12-04”
    }

2010年9月14日 星期二

如何拿到URL的Query String

參考:由GlobalContext可以拿到的值:http://www.projectzero.org/sMash/1.1.x/docs/zero.devguide.doc/zero.core/GlobalContextReference.html

用sMash開發RestFul Service時,也可以在Request中帶上query string,呼叫的方法如下:

http://localhost:8080/basic_info/?abc

在上述的例子中,? 後面的東西就會被當作  query string。

檢視zero.config的設定(如下),表示所有URL是 /basic_info/xxx的東西,都會被送交Test.class這個handeler來處理。

# HTTP port (default is 8080)

/config/http/port = 8080

# Runtime mode (default is "production")

/config/runtime/mode="development"

/config/handlers +=[{

    "events":"GET",

    "handler":"Test.class",

    "conditions":"/request/path=~/basic_info/(.*)?"

}]

再檢視Test.class這個class

import java.io.PrintWriter;
   import zero.core.context.GlobalContext;

public class Test {
    public void onGET(){
        PrintWriter writer = (PrintWriter) GlobalContext.zget("/request/writer");
        String uri = (String) GlobalContext.zget("/request/queryString");
        writer.println("Hello World!");
        writer.println(uri);
    }
}

其中,GlobalContext.zget("/request/writer")這個方法目的為從GlobalContext拿到 Writer;而GlobalContext.zget("/request/queryString");則是從GlobalContext拿到queryString(即?之後的東西)。

啟動 sMash後,輸入連結http://localhost:8080/basic_info/?abc 可得到

Hello World! abc