2017-10-18 80 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