0

使用deadbolt2我有以下控制器功能实现:

def restricted: Action = deadbolt.Restrict(List(Array(USER_ROLE)))() { request =>
  Future {
    val localUser = userProvider.getUser(request.session) // <<< expects a play.mvc.Http.Session
    Ok(views.html.restricted(userProvider, localUser))
  }
}

但它会导致以下编译器错误:

[error] /home/bravegag/code/play-authenticate-usage-scala/app/controllers/Application.scala:26: type mismatch;
[error]  found   : play.api.mvc.Session
[error]  required: play.mvc.Http.Session
[error]       val localUser = userProvider.getUser(request.session)
[error]                                                    ^

基本上,电流request给了我 aplay.api.mvc.Session但我依赖的库(play-authenticate)期待 a play.mvc.Http.Session。有没有办法在两者之间转换?还是另一种获取所需Http的方法?

4

1 回答 1

0

我找到了如何转换play.api.mvc.Sessionplay.mvc.Http.Session

import scala.collection.JavaConversions

val session : Http.Session = 
    new Http.Session(JavaConversions.mapAsJavaMap(request.session.data))

尽管我将不得不继续在任何地方重做......或者编写一个隐式转换 Helper 对象。

更新定义了我自己的隐式转换助手:

package utils

import scala.collection.JavaConversions

object PlayConversions {
  /**
    * Returns the result conversion from a play.api.mvc.Session to a play.mvc.Http.Session
    * @param session play.api.mvc.Session instance
    * @return the result conversion from a play.api.mvc.Session to a play.mvc.Http.Session
    */
  implicit def toHttpSession(session: play.api.mvc.Session) = new play.mvc.Http.Session(JavaConversions.mapAsJavaMap(session.data))
}

更新实际上,这是 Play 机构/首选的方式:

import play.core.j.JavaHelpers

val context = JavaHelpers.createJavaContext(request)
// and now access the Java Http.Session
context.session
于 2016-12-09T20:38:08.367 回答