2012年8月19日 星期日

Jersey - PATH

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

接下來記錄一些比較特別的用法:
1. 動態的在 URL 後面帶入參數:

@GET
@Path("/users/{username}")
public String getUserName(
    @PathParam("username") String userName){
    String helloWord = userName + " Hello!";
  
    return helloWord;
}
*  方法上方的 {username} 可以動態在URL 的後面帶入參數。
*  在方法 getUserName() 中利用 @PathParam("username") 把上述的參數帶進方法中,而 @PathParam 內的字串必須與 { } 內的字串相同。
*  URL 輸入 http://$IP/$PROJECT_NAME/services/jersey/users/Shinko 應該就會得到 Shinko Hello!。

2. 動態的在 URL 後面帶入參數,並且過濾參數:
@GET
@Path("/users2/{username: [a-zA-Z][a-zA-Z_0-9]*}")
public String getUserName2(
    @PathParam("username") String userName){
    String helloWord = userName + " Hello";
  
    return helloWord;
}
*  在方法上方的 [a-zA-Z][a-zA-Z_0-9]* 可以過濾參數,在此範例中 username 必須是大小寫的字母開頭,後面則必須為大小寫字母、底線或是數字,如果不符條件,就會看到 404 的網頁囉!
*  URL 輸入 http://$IP/$PROJECT_NAME/services/jersey/users/Shinko_123 應該就會得到 Shinko_123 Hello!。
*  URL 輸入 http://$IP/$PROJECT_NAME/services/jersey/users/_Shinko_123 應該就會看到 404 的網頁。

沒有留言:

張貼留言