在Play Framework 2.2.2中,我想返回一個Promise。不過,我正在調用一個需要訪問存儲在Http.Context.current()
(當前登錄用戶,JPA連接...)中的變量的函數。如何在播放Promise中使用Http.Context.current()?
當然,由於Promise在另一個線程中執行,因此它無權訪問Http.Context.current()
。我可以保留它在承諾,還是我應該手動恢復它?我應該使用另一種模式嗎?
例子:
public static Promise<Result> getAvailableServices() {
return new Promise.promise(new Function0<Result>(){
@Override
public Result apply() throws Throwable {
// Long operation
List<Services> data = buildResult();
// Render the template
// (The header of the template requires access to
// Http.Context.current().args.get("usermodel"))
return Results.ok(services_template.render(services));
}
});
}
此問題可能被認爲是http://stackoverflow.com/questions/17886630/play-2-1-1-java-can-i-access-http-context-current-from-an-任意異步 – Adrien
我們可以將另一個參數傳遞給Promise.promise(),ExecutionContext。 [HttpExecutionContext](http://www.playframework.com/documentation/2.2.1/api/scala/index.html#play.core.j.HttpExecutionContext)是答案的一部分嗎? – Adrien