所以我正在使用IntelliJ 14.1.1在Scala中使用Play 2.3开发Web应用程序。
问题在于在会话中存储值。我目前有这个:
def authCredentials = Action { implicit request =>
loginForm.bindFromRequest.fold(
formWithErrors => BadRequest(views.html.login(formWithErrors.withError("badlogin","Username or password is incorrect."))),
goodForm => Redirect(routes.AccountController.display).withSession(request.session + ("username" -> goodForm._1))
)
}
然后在我的帐户控制器中:
def display = Action { implicit request =>
request.session.get("username").map { username =>
Ok(views.html.account(User.getUser(username))).withSession(request.session + ("username" -> username))
}.getOrElse(Redirect(routes.LoginController.login)).withNewSession
}
现在在上面的函数中,它只找到用户名并呈现一次帐户页面。问题是在那之后,当我想从帐户页面导航到页面时,例如更改密码页面,甚至是刷新帐户页面,它将重定向回使用新会话登录。
我做错了什么,是否有更好的方法来检查会话是否经过身份验证以访问页面,而不是在每个显示函数上重复代码。
这似乎是一个简单的括号问题,请尝试:
def display = Action { implicit request =>
request.session.get("username").map { username =>
Ok(views.html.account(User.getUser(username))).withSession(request.session + ("username" -> username))
}.getOrElse(Redirect(routes.LoginController.login).withNewSession)
}
实际上,您在任何情况下都在控制器中重置会话,现在withNewSession
调用位于getOrElse
内部,只有在当前会话中找不到用户名的情况下才会发送新会话。