2017-10-18 43 views
0

我想創建一個全局變量,所有控制器都可以訪問。爲此,我創建了一個FrontController類,它從Controller延伸。我所有常用的控制器都是從這個FrontController延伸出來的。在PlayFramework中訪問HTTP上下文

現在我想創建一個變量countryFrontController這是基於主機設置。我試圖從當前的請求中獲取這些信息。

我現在的問題是:如何訪問當前的HTTP上下文?

package controllers; 

import play.mvc.Controller; 

public class FrontController extends Controller { 

    // Country-Code of currenty country --> "ch", "de", "at" 
    private String currentCountry; 

    public FrontController() { 
     this.init(); 
    } 


    private void init() { 
     this.initCountry(); 
    } 


    private void initCountry() { 

     String host = request().host(); 

     // then get country from host 
    } 
} 

因爲當我嘗試這個,我得到的錯誤信息:

Error injecting constructor, java.lang.RuntimeException: There is no HTTP Context available from here 

我認爲問題可能與「要求()調用。

回答

2

您可以使用action截取對控制器中特定/所有方法的調用,並將action中的所有必需對象傳遞給controller

以下爲快速action例如:

public class FetchCountryAction extends play.mvc.Action.Simple { 

    public CompletionStage<Result> call(Http.Context ctx) { 
     String host = ctx.request().host(); 
     String country = getCountry(host); 
     ctx.args.put("country", country); 
     return delegate.call(ctx); 
    } 

} 

而對於controller部分:

@With(FetchCountryAction.class) 
public static Result sampleAction() { 
    String country = ctx().args.get("country"); 
    return ok(); 
} 

請參考下面的link的更多詳細信息actions