Scala Play框架:访问来自QueryStringBindable的消息

时间:2018-09-23 16:14:46

标签: scala playframework

请问您对v2.6.13的Play框架有何帮助。 我试图验证查询字符串参数,因此实现了以下QueryStringBindable:

import play.api.data.validation._ 
import play.api.i18n.Messages 
import play.api.mvc.QueryStringBindable
import scala.util.{Failure, Success, Try}

case class PagingParams(offset: Int, limit: Int)

object PagingParams {

  val DefaultOffset = 1
  val DefaultLimit = 20   
  val OffsetParamKey = "offset"   
  val LimitParamKey = "limit"   
  val ValidationConstraints = Seq(Constraints.min(1), Constraints.max(100000))

  implicit def queryStringBinder(implicit intBinder: QueryStringBindable[Int]) = new QueryStringBindable[PagingParams] {

    override def bind(key: String, params: Map[String, Seq[String]]): Option[Either[String, PagingParams]] = {
      val result = for {
        offset <- Try(intBinder.bind(OffsetParamKey, params).get).recover {
          case _ => Right(DefaultOffset)
        }
        limit <- Try(intBinder.bind(LimitParamKey, params).get).recover {
          case _ => Right(DefaultLimit)
        }
      } yield {
        (offset.right.toOption, limit.right.toOption)
      }
      result match {
        case Success((maybeIndex, maybeLimit)) =>
          ParameterValidator(ValidationConstraints, maybeIndex, maybeLimit) match {
            case Valid =>
              Some(Right(PagingParams(maybeLimit.get, maybeLimit.get)))
            case Invalid(errors) =>
              Some(Left(errors.zip(Seq(OffsetParamKey, LimitParamKey)).map {
                case (ValidationError(message, value), param) => Messages(message, param, value)
              }.mkString(", ")))
          }
        case Failure(e) => Some(Left(s"Invalid paging params: ${e.getMessage}"))
      }
    }

    override def unbind(key: String, pagingParams: PagingParams): String =
      intBinder.unbind(OffsetParamKey, pagingParams.offset) + "&" + intBinder.unbind(LimitParamKey, pagingParams.limit)   
  } 
}

问题是正在运行的应用程序出现以下错误:

  

未找到隐式的MessagesProvider实例。

不幸的是,我找不到如何隐式注入MessagesProvider的任何帮助,以便可以从消息文件中检索消息。

这是我的端点在路由文件中的样子:

GET     /table                      controllers.TableController.index(pagingParams: PagingParams)

非常感谢。如果已经问过类似的问题,请接受我的道歉。

1 个答案:

答案 0 :(得分:0)

如Play documentation中所示,您的控制器类应注入(您可以import com.google.inject.Inject进行注入)ControllerComponents,扩展AbstractControllerI18nSupport:< / p>

class MyController  @Inject()(cc: ControllerComponents)
  extends AbstractController(cc) with play.api.i18n.I18nSupport { 
    ??? //your controller methods
} 

此外,您还需要在视图文件中使用requestHeaderMessageProvider实例:

@(viewsElement: String)(implicit request: RequestHeader, messagesProvider: MessagesProvider)