【问题标题】:Having a custom QueryStringBindable in the scope with Play 2.4.3在 Play 2.4.3 的范围内有一个自定义的 QueryStringBindable
【发布时间】:2016-10-24 19:10:50
【问题描述】:

我想在我的 Play-scala 项目中使用 java.sql.Date 和 Option[java.sql.Date] 作为查询参数,这不是 Play 框架的默认设置。我使用的播放版本是 2.4.3。我有以下(粗略的)课程。

object CustomBinders extends {
  val dateFormat = ISODateTimeFormat.date()

  implicit def dateBinder: QueryStringBindable[Date] = new QueryStringBindable[Date] {
    def bind(key: String, params: Map[String, Seq[String]]): Option[Either[String, Date]] = {
      val dateString: Option[Seq[String]] = params.get(key)
      try {
        Some(Right(new Date(dateFormat.parseDateTime(dateString.get.head).getMillis)))
      } catch {
        case e: IllegalArgumentException => Option(Left(dateString.get.head))
      }
    }

    def unbind(key: String, value: Date): String = {
      dateFormat.print(value.getTime)
    }
  }
}

然后在 Build.scala 我有

import play.sbt.routes.RoutesKeys

object Build extends Build {
  RoutesKeys.routesImport += "binders.CustomBinders.dateBinder"
  RoutesKeys.routesImport += "binders.CustomBinders.optionDateBinder"

但是,例如,如果我使用 Option[Date] 定义查询参数,则会出现错误

No QueryString binder found for type Option[java.sql.Date]. Try to implement an implicit QueryStringBindable for this type.

所以这显然不是范围。我应该如何定义 Binder 以便它们存在于范围内?我找不到这方面的 2.4 文档,但 2.5-documentation 没有说明需要将它们添加到 Build.scala

【问题讨论】:

    标签: scala playframework query-string playframework-2.4 querystringparameter


    【解决方案1】:

    所以显然 Build.scala 不是正确的地方......尽管有些文档告诉把它放在那里。在 build.sbt 中时

    routesImport += "binders.CustomBinders._"
    

    项目编译得很好。还修复了 Binder 原帖中的一些错误。

    【讨论】:

    • 别忘了导入import play.sbt.routes.RoutesKeys.{routesImport}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    • 2019-09-21
    • 2010-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多