2012年10月27日 星期六

Plugins/Validation - Basic

參考網址:bassistance.de/jquery-plugins/jquery-plugin-validation/
這章主要是記錄搭配 jQuery Validation Plugin 做到 驗證表單 的功能,這是一個相當好用又便於擴充的套件,基本上我用過一次之後就愛上它了,所以在這邊分享給大家也順便做個紀錄。
只要有表單的地方幾乎就是會有驗證,有必填欄位、欄位長度限制、只能輸入數字等多種可能的驗證,要寫一堆驗證的邏輯、控制錯誤訊息的位置以及可以重複利用並且應付更種狀況的程式,可能就會花上許多的時間,既然已經有設計很棒的套件,為了表示對開發者的敬意,當然就要用力地使用它了,以下是簡單的範例:

Test Validation Plugin

Account :
Password :
Re-Password :
Age :
Email :
*  這是一個輸入基本資料的表單,其中最需要注意的 name 這個屬性,所有需要驗證的欄位都需要有這個屬性,這是 Validation Plugin 中用來辨識各個欄位的重要ID。


接下來就要利用 Validation Plugin 去綁訂個欄位,定義它們所需要驗證的邏輯以及驗證失敗時的錯誤訊息:
 
    $('#validator_form').validate({
    rules:{
        account:{ required : true,  minlength: 3},
        password:{ required : true, rangelength: [4, 20]},
        re_password:{ required : true, equalTo: "#password"},
        age:{ required : true, number: true},
        email:{ required : true, email: true}
    },
    submitHandler:function(){
        alert("Account : " + $("#account").val() + 
         ", Password : " + $("#password").val() +
         ", Age : " + $("#age").val() + 
         ", Email : " + $("#email").val());
    },
    messages : {
        account : {
            minlength : "This field requires at least three characters"
        },
        password : {
            rangelength : "This field requires 4-20 characters"
        },
        re_password : {
            equalTo: "Please repeat your password"
        },
        age : {
            number : "This field only accepts numbers"
        },
        email : {
            email : "Please enter a valid email"
        }
    }
    });
    $("#submit_button").click(function(){
        $("validator_form").submit();
    });

*  首先要先去 bassistance.de/jquery-plugins/jquery-plugin-validation/ 下載 Validation Plugin 並載到你要用的頁面中。
*  $('#validator_form').validate({...}):這是 Validation Plugin 的初始化,validator_form 對應到上面 html 中表單的 id。
*  rules 定義的是個欄位要驗證的邏輯,在套件中已經實做好許多常用的規則,在官網上可以看到有哪些可以用,使用方式是針對各欄位的 name 並定義要用的規則,在此範例中每個欄位都有定義 required,顧名思義就是必填欄位,而在各個欄位中還有定義其他驗證,像是 Re-Password 中的 equalTo: "#password",就是指此欄位的值必須與欄位 id 為 password 的值相同才行,這些規則就如字面上所表示,相當好理解。
*  submitHandler 裡的方法,是在所有定義的欄位都通過驗證才會執行,通常就是把各欄位的值整理一下並送往後端做處理。
*  messages 就是定義各欄位發生驗證錯誤時所需要給使用者看的訊息,如果是用官方中定義好的規則,那預設就已經有寫好個規則的錯誤訊息,如果要客製化自己的錯誤訊息,只要針對各欄位的 name 以及這欄位中定義好的規則裡面寫上客製化的訊息即可。

下面是成功後的圖片,後面我們會繼續介紹此套件中其他可以使用的屬性及方法:



2012年9月25日 星期二

Jersey - File Upload

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

我們在一般的 Web Service 上面一定會上傳檔案的功能,可以利用 @Context HttpServletRequest 來拿到上傳的物件:

@POST
@Path("/users/upload/avatar")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_HTML) 
public String uploadAvatar(
    @Context HttpServletRequest request) throws   JSONException{
  
    String filePath = "D:\\avatar\\";
    String fileName = "";
    JSONObject jsonOutput = new JSONObject();
    List<string> errorList = new ArrayList<string>();
  
    if (ServletFileUpload.isMultipartContent(request)) {

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("utf-8");
        try {
            List<fileitem> items = upload.parseRequest(request);
            Iterator<fileitem> iter = items.iterator();  
    
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (!item.isFormField() && item.getSize() > 0) {   
                    fileName = item.getName();
                    item.write(new File(filePath + fileName));
                }else {
                    errorList.add("Upload item was not correct");
                }
            }
        } catch (FileUploadException e) {
            errorList.add("Parse request error : " + e.getMessage());
        }catch (Exception e) {
            errorList.add("Have exception : " + e.getMessage());
        }
    } else {
        errorList.add("Upload item was not correct");
    }
    if(errorList.size() != 0){
        jsonOutput.put("statuscode", 500).put("msg", errorList.toString());
    }else{
        jsonOutput.put("statuscode", 200).put("path", filePath + fileName);
    }
    return jsonOutput.toString();
}
*  @Consumes(MediaType.MULTIPART_FORM_DATA) 是代表只接受內容編碼為 multipart/form-data 的需求。
*  上傳的物件則封裝在 HttpServletRequest request 裡面。
*  在這我是利用 org.apache.commons.fileupload 來處理上傳的物件,詳細內容可以參考 Apache 官方網站 http://commons.apache.org/fileupload/。
*  最後把上傳的檔案存在 D:\avatar\(請先建立此資料夾) ,並在回傳的JSON裡面存有此物件的路徑。

接下來是在前端實作上傳檔案的 UI:

Test File Upload

*  enctype="multipart/form-data" 代表有檔案要上傳,不要對字符編碼,跟上面的 MediaType.MULTIPART_FORM_DATA 相對應。

還有控制上傳的 Ajax :
$(function() {
    $("#uploadFileButton").click(function(){
        $("#uploadForm").attr("action",
            "http://YOUR_IP/YOUR_PROJECT/services/jersey/users/upload/avatar");
        $("#uploadForm").submit();
    });
    $("#uploadForm").ajaxForm({
        url: $("uploadForm").attr("action"),
        beforeSubmit: showRequest,
        type: "post",
        dataType: "json", 
        success: uploadCallback
    });
});
function  showRequest(formData, jqForm, options) {  
    console.log( "Form element's ID : " +  $(jqForm).attr("id") );
    return  true ;  
}
function uploadCallback(responseJson, statusText, xhr, $form ){
    if(statusText == "success" && responseJson && responseJson.statuscode == 200){
        console.log("Upload succeeded!!");
        $("#avator_path").html(responseJson.path).show();
    }else{
        console.log("Upload failed!!");
    }
}
*  這邊我們是利用 ajaxForm 的套件來完成 ajax 上傳,相當簡單好用,相關說明可以參考 http://www.malsup.com/jquery/form/#getting-started。
*  要注意 Form 的 action 要跟上面 Jersey 的 @Path("/users/upload/avatar") 相對應 。

2012年9月12日 星期三

Jersey - Context

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

有時我們在後端接收到需求後,會需要知道 URL 的資訊,或是想要拿到 Context 或是 Session 的參數,這時就可以利用 @Context 來拿到相關的物件:

@Context
private UriInfo uri;

private UriInfo getUri() {
    return this.uri;
}
@GET
@Path("/users/get/uri")
@Produces(MediaType.APPLICATION_JSON)
public String getURIInformation()throws JSONException {
        
    String contextRoot = getUri().getBaseUri().toString();
    String absolutePath = getUri().getAbsolutePath().toString();
     
    return new JSONObject().put("statuscode",200).
        put("contextRoot", contextRoot).
            put("absolutePath", absolutePath).toString();
}

@GET
@Path("/users/get/httpHeaders")
@Produces(MediaType.APPLICATION_JSON)
public String getHttpHeaders(@Context HttpHeaders headers) throws JSONException{

    String userAgent = headers.getRequestHeader("User-Agent").toString();
        
    return new JSONObject().put("statuscode",200).
        put("userAgent", userAgent).toString();
}
*  @Context 通常可以用來取得 UriInfo、HttpHeaders、HttpServletRequest 以及 ServletContext 等物件,可以在 http://jsr311.java.net/nonav/releases/1.1/javax/ws/rs/core/Context.html 參考相關API。
*  要得到上述物件的方法有兩種,一是像宣告成員變數一樣,就像上面範例中取得 UriInfo 物件的方式;另一種則是直接當參數傳進方法中,就像上面範例中取得 HttpHeaders 物件的方式。

接下來是取得 HttpServletRequest 以及 ServletContext 的範例:
@GET
@Path("/users/get/httpRequest")
@Produces(MediaType.APPLICATION_JSON)
public String getHttpRequest(
    @Context HttpServletRequest req) throws  JSONException{

    HttpSession session= req.getSession(true);
    String sessionID = session.getId();
        
    return new JSONObject().put("statuscode",200).
        put("sessionID", sessionID).toString();
}
    
@GET
@Path("/users/get/servletContext")
@Produces(MediaType.APPLICATION_JSON)
public String getHttpRequest(
    @Context ServletContext context) throws JSONException{

    String serverInfo = context.getServerInfo();
        
    return new JSONObject().put("statuscode",200).
        put("serverInfo", serverInfo).toString();
}

Jsersey - CookieParam & HeaderParam

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

Jersey 可以把 Cookie 跟 Header 的值帶進方法的參數裡,不過必須先知道對應的key才行:

@GET
@Path("/users/get/cookieAndHeader")
@Produces(MediaType.APPLICATION_JSON)
public String getCookieAndHeader(
    @CookieParam("JSESSIONID") String sessionID,
    @HeaderParam("User-Agent") String userAgent)throws JSONException {
        
    return new JSONObject().put("statuscode",200).
        put("sessionID",sessionID).put("userAgent",userAgent).toString();
}
*  方法參數裡的 @CookieParam("JSESSIONID") 就是要把 cookie 中 JSESSIONID 的值帶進來。
*  方法參數裡的 @HeaderParam("User-Agent") 就是要把 header 中 User-Agent 的值帶進來。

接下來我們就利用 jQuery ajax 來做驗證:
$.ajax({
    type:"GET",
    url:"http://$IP/$PROJECT_NAME/services/jersey/users/get/cookieAndHeader",
    dataType: "json",
    data: "",
    success: function(data){
        if(data){
            console.log("SUCCEEDED");
            console.log("status code : " + data.statuscode);
            console.log("session ID : " + data.sessionID);
            console.log("user agent : " + data.userAgent);
        }else{
            console.log("NO RETURN");
        }
    },
    error: function(){
        console.log("ERROR");
    }
});

*  執行成功的話,console 會顯示你的 session ID 以及瀏覽器的資訊。

2012年9月11日 星期二

Jersey - FormParam

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

HTML 裡的 form 可以讓我們帶資料到後端去,form 裡面的資料可以直接帶進宣告好的 Jersey 方法裡面:

Name : Age :
*  form 的方法這邊選擇用 POST。

接下來我們就要宣告好 Jersey 來處理這個表單的需求:
@POST
@Path("/users/register")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public String registerUser(
    @FormParam("name") String name,
    @FormParam("age") int age)throws JSONException {
   
        //Use name and age to register user//
        return new JSONObject().put("statuscode",200).
            put("name",name).put("age",age).toString();
}
*  方法上面配合 form 的方法宣告為 POST 。
*  @Consumes  裡面宣告的 MediaType.APPLICATION_FORM_URLENCODED 指的就是只接受表單類型的資料格式。
*  方法參數裡的 @FormParam 指的就是要把 form 裡的資料當參數傳進方法裡面,@FormParam 後面括弧裡 "name" 以及 "age" 必須對應到 form 裡 input 的 name,而括弧後面 String 的變數名就可以任意取名。
*  執行成功的話,畫面上會顯示 {"statuscode":200,"name":"shinko","age":28}。

Jersey - QueryParam & MatrixParam

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

HTTP 的 GET 方法裡面,參數都是帶在 URL 的後面,像是:
http://$YOUR/$PROJECT_NAME/services/jersey/users/delete?department=HR&id=2
這些參數可以直接帶進宣告好的 Jersey 方法裡面:

@GET
@Path("/users/delete")
@Produces(MediaType.APPLICATION_JSON)
public String deleteUser(
    @DefaultValue("IT") @QueryParam("department") String department,
    @QueryParam("id") int id)throws JSONException {
   
        //Use department and id to delete user//
        return new JSONObject().put("statuscode",200).
            put("department",department).put("id",id).toString();
}
*  方法參數裡的 @QueryParam("department") 就是宣告:URL 的 ? 後面如果有參數名叫 "department" 就把參數帶進來,而 String 後面的參數名就可以自訂。
*  方法參數裡的  @DefaultValue("IT") 是宣告:如果 URL 的 ? 後面沒有可以匹配 "department" 的參數時,就用 "IT" 來代替。

除了上述參數格式以外,Jersey 還有提供另外一種格式:
http://YOUR_IP/YOUR_PROJECT/services/jersey/users/delete2;department=HR;id=2
參數之間以分號格開,取得參數的方法與上面類似:
@GET
@Path("/users/delete2")
@Produces(MediaType.APPLICATION_JSON)
public String deleteUser2(
    @DefaultValue("CA") @MatrixParam("department") String department,
    @MatrixParam("id") int id)throws JSONException {
   
        //Use department and id to delete user//
        return new JSONObject().put("statuscode",200).
            put("department",department).put("id",id).toString();
}
*  除了參數裡的 @MatrixParam 以外 ,皆與 @QueryParam 相同。

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 做溝通的一個流程囉。