2012-05-22 39 views
1

我非常需要我的用戶對象,所以我想我會將它存儲在緩存中。由於我不知道它何時從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,我做錯了什麼?

回答

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")

0

在斯卡拉的工作原理是代碼:

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回報選項[字符串]

request.session.apply返回字符串

play framework 2 scala Play.api.mvc.Session