【问题标题】:Scala Play 2, passing request to methodScala Play 2,将请求传递给方法
【发布时间】:2012-06-25 23:50:51
【问题描述】:

我有一个Play 2.0 应用程序

TestController.scala

def foo(p1: String) = Action {implicit request =>
  Ok(bar(p1))
}

private def bar(p1: String) = {
//access request parameter here
}

有没有办法使用implicitrequest 传递给bar

【问题讨论】:

    标签: scala playframework playframework-2.0


    【解决方案1】:

    是的,您可以:

      def foo(p1: String) = Action { implicit request =>
        Ok(bar(p1))
      }
    
      private def bar(p1: String)(implicit req: RequestHeader) = "content"
    

    代码:

    Action { implicit request
    

    在 Action 对象上调用此方法:

    def apply(block: Request[AnyContent] => Result): Action[AnyContent] = {
    

    所以,你所说的“请求”匹配名为“块”的参数。这里的“隐式”是可选的:它使“请求”值可作为其他方法/函数调用的隐式参数。

    “bar”函数中的隐式表示它可以从隐式值中获取“req”的值,并且不一定需要显式传入。

    【讨论】:

    • 谢谢亚当,这行得通。后续问题,是否需要将隐式作为柯里化参数传递?
    • 在 scala 中,它是参数 list,而不是参数,这是隐式的。我不确定这样做的动机。
    • scala> 隐式 val i = 1 i: Int = 1 scala> 隐式 val s = "hi" s: java.lang.String = hi scala> def concat(implicit x:Int, y: String) = x + y concat: (隐式 x: Int, 隐式 y: String)String scala> concat res0: String = 1hi
    • 使用 play 2.0.3 时,当我执行 def foo[A](i: Int)(implicit request: Request[A]): Baz = { ... } 时,我不断收到“在这里找不到任何 HTTP 请求”。通过将 Request[A] 更改为使用 RequestHeader 来修复此错误。谢谢 Adam Rabung - 你的信息帮了大忙。
    • 使用 play 2.4.6,我需要使用 Request[AnyContent]
    猜你喜欢
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 2010-12-30
    相关资源
    最近更新 更多