2017-02-11 66 views
1

我想在處理它之前驗證LIFT中的REST請求(GET和PUT)。即我需要檢查請求是否有參數請求者。如果不需要回應異常說缺少參數。你能不能讓我知道如何做到這一點。攔截電梯休息請求並驗證參數

回答

0

有幾件事你可以做。這兩個我會嘗試將是一個輔助函數,將換你REST調用,這樣的:

def checkParam(r:Req):Boolean = { 
    r.param("paramName").isDefined 
} 

def requireParams[T<:LiftResponse](r:Req)(methodBody: => T):LiftResponse = { 
    if(checkParam(r)) 
     methodBody 
    else 
     InMemoryResponse("Parameters not specified".getBytes(), List("content-type" -> "text/plain"), Nil, 500) 
} 

功能將檢查參數和返回一個錯誤,如果它不能正常工作,或執行如果呼叫它確實如此。在您的REST調用,你可以使用它像:

case "location" :: Nil Get req => requireParams(req){ 
    //your rest body 
} 

或者,你很可能對整個RestHelper假設你要檢查每一個方法調用guard,這樣的事情可能工作:

val ensureParams: PartialFunction[Req, Unit] = { 
    case r if (r.get_? || r.put_?) && checkParam(r) => 
    case r if (!r.get_? && !r.put_?) => 
    } 

並保護您的RestHelper實例在啓動用:

LiftRules.dispatch.append(ensureParams guard YourRestHelper) 

我沒有測試上面的代碼,所以可能會有一些錯誤 - 但希望它應該幫助你開始。

+0

感謝jcern,我用RestHelper和guard來阻止參數丟失時的請求。當參數不可用時,我需要自定義消息或錯誤頁面。我們應該怎麼做? – Prasad

+0

如果您可以嘗試在[提升列表](https://groups.google.com/forum/#!forum/liftweb)上詢問這些其他詳細信息,我們可以在其中跟進。或者你可以問一個額外的後續問題,我可能會提供更多的細節。 –