【问题标题】:Play 2.5 type mismatch Session type播放 2.5 类型不匹配 Session 类型
【发布时间】:2016-12-09 20:14:16
【问题描述】:

使用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 给了我一个play.api.mvc.Session,但我依赖的库 (play-authenticate) 期待一个play.mvc.Http.Session。有没有办法在两者之间转换?还是另一种获取所需 Http 的方法?

【问题讨论】:

    标签: scala playframework play-authenticate deadbolt-2


    【解决方案1】:

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

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

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

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多