I'd like to create a global variable which all controllers can access. For this I've created a FrontController
class which extends from Controller
. All my usual controllers then extend from this FrontController
.
Now I want to create a variable country
in the FrontController
which is set based on the host. And this information I try to get from the current request.
My question now is: How can I access the current HTTP Context?
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
}
}
Because when I try this I get the error message:
Error injecting constructor, java.lang.RuntimeException: There is no HTTP Context available from here
I think the problem may be with the 'request()' call.
You can use an action
to intercept the call to an specific / all methods in a controller and pass any necessary objects from the action
to the controller
.
Following is a quick action
example:
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);
}
}
And for the controller
part:
@With(FetchCountryAction.class)
public static Result sampleAction() {
String country = ctx().args.get("country");
return ok();
}
Refer to the following link for more details on actions
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.