简体   繁体   中英

Get the base url of a Play application

I want to obtain the current base url of an application which usually http://localhost:9000/ at localhost and http://mydomain.com at a server. If the future I might start using https.

How can I do this?

What version of Play Framework are you using ?

If you are using Play 1.x, you should manually specify the base url of your application using an application.conf variable. This is the way I do in order to retrieve base url for my applications. For example :

application.baseUrl=http://localhost:9000
%devcloud.application.baseUrl=http://dev-url.com
%prod.application.baseUrl=http://prod-url.com

With Play Framework 2.x, you could use additional configuration file (thus variables values depending on the environment - prod, dev, test ...), as explained here : http://www.playframework.com/documentation/2.2.x/ProductionConfiguration

These solutions work especially if you do not want to depend on an Action or a Controller. Else, you can retrieve the absolute URL using the Request within the Action.

然后尝试获取play.Play.application().configuration().getString("application.baseUrl")play.Play.application().configuration().getString("application.baseUrl")

Currently play.Play.application().configuration().getString("application.baseUrl"); is depricated in play latest version. so here is the latest solution to the problem :

First Inject the configuration into the class :

   @Inject
    Configuration configuration;

Then use it like :

String baseUrl = configuration.getString("application.baseUrl");

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM