如何在Scalatra中使用前置过滤器中的参数?

时间:2013-10-29 17:53:38

标签: scala scalatra

我有一个全局过滤器,我想在基于scalatra的API中实现。为了简单起见,我想要一个带有变量foo和一个值条的API调用来抛出403.我用继承链启动了这个问题。

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变量总是为空,无论是否存在param。是否有更好的方法或是否有另一种方法从过滤器中提取参数?

1 个答案:

答案 0 :(得分:1)

在前一种方法中没有填写参数。您可以覆盖调用方法。

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)
        }
    }
}