【问题标题】:Serving static page from custom scala action in Play Framework从 Play Framework 中的自定义 scala 操作提供静态页面
【发布时间】:2014-03-17 18:55:56
【问题描述】:

我是 scala 的新手,但对使用 Java 中的 play 框架有一些经验。我添加了 SecureSocial 身份验证库,它定义了 SecuredACtion,它似乎工作正常。但是,我无法理解 scala 代码中自定义操作中的预期内容。

这是我的控制器类。理想情况下,“index”会以某种方式简单地将经过身份验证的请求重定向到“unprotectedIndex”,但这似乎是不可能的。因此,如果没有,下一个最好的办法就是直接从安全操作内部提供文件,但这也行不通。

我的代码中缺少什么?

object Application extends Controller with securesocial.core.SecureSocial {
  // this doesn't compile, but it's a long scala exception that I don't know how to fix.
  def index = SecuredAction { implicit request =>
    Assets.at("/public", "index.html").apply(request) 
  }

  def unprotectedIndex = Assets.at("/public", "index.html")

}

似乎它期待一个 SimpleResult 但得到一个 Future[SimpleResult] - 这感觉不应该很复杂,但我错过了什么?

【问题讨论】:

  • 请同时查看我的编辑

标签: java scala playframework securesocial


【解决方案1】:

看来您使用的是 play framework 2.2。有一些变化,大多数方法返回Future[SimpleResult] 而不仅仅是ResultSimpleResult。你可以检查你是否可以这样做:def index = SecuredAction.async {...}(但我几乎可以肯定你不能)。

您可以使用这种方法使其正常工作:

import scala.concurrent.Await
import scala.concurrent.duration._

def index = SecuredAction { implicit request =>
  Await.result(Assets.at("/public", "index.html").apply(request), 5 seconds) //you can specify you maximum wait time here
}

编辑

还要简化一件事:

Await.result(unprotectedIndex(request), 5 seconds)

因此,您可以通过 index 操作调用您的 unprotectedIndex

【讨论】:

  • 酷,谢谢。这比我发现的 .value.get.get 更有意义。
  • 所以,实际上 SecuredAction.async 工作得很好。它在块中接受了 Future,而不必进行任何 Await 调用或其他任何操作。完美。
  • 哦,那很好。我只是不确定 SecuredAction 是如何实现的,所以假设它只是一个 Action
【解决方案2】:

因此,仅通过查看我的 IDE 中的语法突出显示,我就能够得到一些似乎可以编译和工作但对我来说看起来很错误的东西。

我改成这样了:

def index = SecuredAction { implicit request =>
    Assets.at("/public", "index.html").apply(request).value.get.get
  }

这是正确的方法吗?我觉得很奇怪,我只是不熟悉成语吗?

【讨论】:

  • 您在Future 上调用value,它返回Option[Try[T]],其中T 是通用的(在本例中为Result 或其子类型之一)。这可能会导致NoSuchElementException,因为您试图立即获取Future 的值,而不是在回调或其一元函数(如mapflatMap)中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-09
  • 2014-08-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 2019-11-14
相关资源
最近更新 更多