2012年9月11日 星期二

Jersey - POST & Consumes & Produces

參考網址:http://jersey.java.net/nonav/documentation/latest/user-guide.html#d4e380
這章主要是記錄 Annotation 中的 POST ,GET 基本的用法在 Jersey - Hello World 中已有記錄,以下將延續上一篇的結構。

HTTP 的 method 裡面,最常用的就是 GET 跟 POST,POST 把要傳送的資料藏起來,以安全性而言比 GET 安全一點,下面是範例:
1. 動態的在 URL 後面帶入參數:

@POST
@Path("/users/login")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String getUserName(
    InputStream is)throws JSONException {
    StringBuffer buffer = null;
    if (is != null) {
    buffer = new StringBuffer();
    try {
     InputStreamReader isr = ;
     Reader in = new BufferedReader(
                new InputStreamReader(is,"UTF-8"));
     int ch;
     while ((ch = in.read()) > -1) {
         buffer.append((char)ch);
     }
     in.close();
 } catch (IOException e) {
            return null;
 }
    } else {
 return null;
    }
    JSONObject requestBodyJson = new JSONObject(buffer.toString());
    String username = requestBodyJson.getString("username");
    String password = requestBodyJson.getString("password");
    if(username.equals("jerseyuser") && password.equals("jerseypass")){
        return new JSONObject().put("statuscode",200).toString();
    }else{
        return new JSONObject().put("statuscode",500).toString();
    }
}
*  方法上的 @POST 就是宣告:除了 URL 要正確外,一定要用 POST 才會由這個方法處理。
*  方法上的 @Consumes 是宣告 POST Body 裡面的格式,可以是純文字、XML 格式或是 JSON 格式等, 如果 POST 過來的 content-type 不符合宣告,就會噴 415 Unsupported Media Type。
*  方法上的 @Produces 是宣告回傳值的格式,可以是純文字、XML 格式或是 JSON 格式等,如果回傳的格式不對,對方就接不到 HTTP status code 200 的回應。
*  方法內容的一開始先將傳進來的 InputStream 轉成文字再轉為 JSON 物件,再來就可以擷取傳來的資訊。
*  利用 jQuery ajax 來驗證,在這僅說明 ajax 的寫法:
var postData = 
    {
        "username":$("#useranme").val() ,
        "password":$("#password").val() 
    }
$.ajax({
    type:"POST",
    url:"$IP/$PROJECT_NAME/services/jersey/users/login",
    contentType: "application/json",
    dataType: "json",
    processData: false,
    data: JSON.stringify(postData),
    success: function(data){
        if(data){
     console.log(data.statuscode);
     console.log("SUCCEEDED");
        }else{
     console.log("NO RETURN");
 }
    },
    error: function(){
        console.log("ERROR");
    }
)};
*  ajax 裡的 type:"POST" 對應 Java 裡的 @PATH。
*  ajax 裡的 contentType 對應 Java 裡的 @Consumes。
*  ajax 裡的 dataType 對應 Java 裡的 @Produces。
這樣就完成利用 ajax 與 jersey 做溝通的一個流程囉。

沒有留言:

張貼留言