2013-01-18 78 views
1

我正在開發一個RESTlet API(JAVA),並且我創建了一個自定義授權過濾器,可以在將所有請求傳遞到路由器之前運行所有請求。在我的請求中,我始終將會話ID作爲請求屬性傳遞,例如RESTlet授權過濾器

http://localhost:8080/myAPI/{sid}/someResource/ 

現在,在我的功能擴展ServerResource,我可以做這樣的事情很容易地提取{SID}

String sid = (getRequestAttributes().containsKey("sid")) ? getRequestAttributes().get("sid").toString() : ""; 

我的問題是,在我的授權功能,其中過濾器(授權功能不是通過路由器調用,但在我的主要函數中調用createInboundRoot()函數),我不能使用相同的方法來提取{sid}。我已經使用request.getResourceRef()。getSegments()的字符串操作創建了一個解決方法,但是必須有更好的方法嗎?

任何幫助將不勝感激!

感謝

回答

3

您可以創建一個公共父類ServerResource任何孩子。像這樣:

public class CommonParentResource extends ServerResource 
{ 
    // class definition 
} 

然後覆蓋在它的ServerResource類的doInit()方法。

public class CommonParentResource extends ServerResource 
{ 
    public void doInit() 
    { 
     boolean authorized=false; 

     String sid = getRequestAttributes().containsKey("sid") ? (String)getRequestAttributes().get("sid") : StringUtils.EMPTY; 

     // Authorization logic here. 

     if(!authorized)//after authorization process completed. 
     { 
      getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); 
      getResponse().setEntity(/*Representation carrrying message for unauthorized user*/); 
     } 
    } 
} 

現在,任何新的子類的要執行此授權檢查ServerResource,必須擴展這個CommonParentResource類。就像這樣:

public class FriendsListResource extends CommonParentResource 
{ 
    @Get 
    //...... 
} 

兩點重要的是在這裏:

  1. 任何子類的ServerResourcedoInit()調用帶有註釋的任何方法被調用之前@Get/@Post/...

  2. (小心)如果您不使用此聲明:

    getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); 
    

    也就是說,如果你不設置狀態響應的一個錯誤,則註釋的方法,用@Get/@Post/@Put/...將調用!但是如果你的程序設置響應錯誤狀態的狀態,那麼@Get/@Post/@Put/......不會得到執行,最終用戶將看到所代表的錯誤消息:

    getResponse().setEntity(/*Representation carrrying message for unauthorized user*/); 
    
+0

謝謝阿布舍克!這是一個很好的答案。我給了這一槍。 – kvheerden