Global类中的访问会话

时间:2012-05-22 20:26:41

标签: playframework-2.0

我非常需要我的用户对象,所以我想我会将它存储在Cache中。由于我不知道何时从Cache中销毁它,我将它作为interceptor。所以我定义了以下代码:

@Override
public Action<?> onRequest(Request request, Method actionMethod) {
    // find the user based on the userId that is stored in the session
    // scope.
    String userId = session.get("user"); // does not work
    User loggedInUser = (User) Cache.get(userId);
    if (loggedInUser == null) {
        loggedInUser = User.getUerById(userSyscode);
    }
    return super.onRequest(request, actionMethod);
}

我以为我可以使用:

session.get("user");

但在我看来,session无法从Global class访问,我做错了吗?

2 个答案:

答案 0 :(得分:7)

我遇到了类似的问题并用“动作组合”解决了这个问题。 http://www.playframework.org/documentation/2.0.1/JavaActionsComposition

或者,这是您要覆盖的onRequest的代码,因此我认为您可以执行相同的操作,只需将代码放在call方法中。

public Action onRequest(Request request, Method actionMethod) {
  return new Action.Simple() {
    public Result call(Context ctx) throws Throwable {

      /* your code here */

      return delegate.call(ctx);
    }
  };
}

我不知道session是否可以直接使用,但此时您可以从ctx变量获取它。我认为它会像ctx.session().get("user")

答案 1 :(得分:0)

在scala中使用此代码:

override def onRouteRequest(request: RequestHeader): Option[Handler] = {
    if(!request.session.get("email").isEmpty){
        //I have session with email
        request.session.apply("email") //this is for getting session
    }
}

request.session.get返回选项[String]

request.session.apply return String

play framework 2 scala Play.api.mvc.Session

相关问题