2013-10-29 26 views
0

我有一個全局過濾器,我想在我的基於Scalatra的API中實現。爲了簡單起見,我想要任何一個帶有一個帶有一個值欄的變量foo的API調用來引發一個403.我用一個繼承鏈開始了這個問題。如何在Scalatra過濾器中使用參數?

class NoFooBarRouter extends ScalatraServlet{ 
    before() { 
     if(params.getOrElse("foo", "") == "bar") //params is empty here. 
      halt(403, "You are not allowed here") 
     else 
      pass() 
    } 
} 

class APIRouter extends NoFooBarRouter{ 
    get("/someurl/:foo") { 
     "Hello world!" 
    }   
} 

這不起作用。在調試過程中,我注意到params變量總是空的,無論是否有參數。有沒有更好的方法,還是有另一種方法從前過濾器中提取參數?

回答

1

參數在前面的方法中沒有填寫。您可以覆蓋invoke方法。

class NoFooBarRouter extends ScalatraServlet{ 
    override def invoke(matchedRoute: MatchedRoute): Option[Any] = { 
     withRouteMultiParams(Some(matchedRoute)){ 
      val foo = params.getOrElse("foo", "") 
      if(foo =="bar") 
       halt(403, "You are not authorized for the requested client.") 
      else 
       NoFooBarRouter.super.invoke(matchedRoute) 
     } 
    } 
} 
相關問題