gpt4 book ai didi

Scala Play 2.5 表单 bindFromRequest : Cannot find any HTTP Request here?

转载 作者:行者123 更新时间:2023-12-04 17:16:27 25 4
gpt4 key购买 nike

我有一个这样实现的 Controller 操作:

def doChangePassword = deadbolt.Restrict(List(Array(Application.USER_ROLE_KEY)))() 
{ request => // <<<<<<<<<<<< here is the request
Future {
val context = JavaHelpers.createJavaContext(request)
com.feth.play.module.pa.controllers.AuthenticateBase.noCache(context.response())

val filledForm = Account.PasswordChangeForm.bindFromRequest
// compilation error here, it can't see the request ^^^^^^^

if (filledForm.hasErrors) {
// User did not select whether to link or not link
BadRequest(views.html.account.password_change(userService, filledForm))
} else {
val Some(user: UserRow) = userService.getUser(context.session)
val newPassword = filledForm.get.password
userService.changePassword(user, new MyUsernamePasswordAuthUser(newPassword), true)
Redirect(routes.Application.profile).flashing(
Application.FLASH_MESSAGE_KEY -> messagesApi.preferred(request)("playauthenticate.change_password.success")
)
}
}
}

上面的实现导致编译错误:
[error] /home/bravegag/code/play-authenticate-usage-scala/app/controllers/Account.scala:74: Cannot find any HTTP Request here
[error] val filledForm = Account.PasswordChangeForm.bindFromRequest
[error] ^
[error] one error found

但是,如果我将第 2 行更改为:
{ request => // <<<<<<<<<<<< here is the request 


{ implicit request => // <<<<<<<<<<<< here is the request 

然后它编译......但为什么呢?

最佳答案

您要找的是Implicit Parameters .简而言之:

隐式参数可以像常规或显式参数一样传递。如果您没有明确提供隐式参数,那么编译器将尝试为您传递一个。隐式可以来自不同的地方。来自常见问题 Where does Scala look for implicits? :

  1. First look in current scope
    • Implicits defined in current scope
    • Explicit imports
    • wildcard imports
  2. Now look at associated types in
    • Companion objects of a type
    • Implicit scope of an argument’s type (2.9.1)
    • Implicit scope of type arguments (2.8.0)
    • Outer objects for nested types
    • Other dimensions


第 1 项下的隐式优先于第 2 项下的那些。

通过标记 requestimplicit在您的示例中,您声明了“在当前范围内隐式定义”。您需要有一个隐式请求,因为 bindFormRequest “要求”你通过一个。看它的签名:
bindFromRequest()(implicit request: Request[_]): Form[T]

现在你有一个 implicit request在作用域中,编译器会自动将其传递给 bindFormRequerst .

正如我在开头提到的,您也可以通过 request明确地:
val filledForm = Account.PasswordChangeForm.bindFromRequest()(request)

在后一种情况下,无需声明 requestimplicit因为你显然是路过 request明确地。两种变体是相同的。这取决于你喜欢哪一种。

关于Scala Play 2.5 表单 bindFromRequest : Cannot find any HTTP Request here?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41090946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com