這章主要是記錄 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 相同。
沒有留言:
張貼留言