Retrieving port number in Play Framework 2 app

后端 未结 3 2179
心在旅途
心在旅途 2021-01-05 09:49

The question is: how do I retrieve the port number that play is listening on, no matter how it was defined (configuration, command line argument, or not at all).

Thi

相关标签:
3条回答
  • 2021-01-05 09:58

    I'm using this Scala snippet to determine Play's listen port. Unfortunately I had to hard code some default values, in case -Dhttp.port=... is not specified.

    val listenPort =
      if (!Play.isTest) {
        System.getProperty("http.port", "9000")
      }
      else {
        // Not on classpath: play.api.test.Helpers.testServerPort
        // Instead, duplicate its implementation here:
        System.getProperty("testserver.port", "19001")
      }
    

    I also wonder if there is no better way, e.g. Play.port but I haven't found anything — well except for your question :-)

    (In your example, it should be -Dhttp.port=80 not -Dhttp.port 80.)

    0 讨论(0)
  • 2021-01-05 10:05

    Running in dev mode you need to use doubled notation

    play -Dhttp.port=80 "run 80"
    

    Unfortunately you have to do the same for default port

    play -Dhttp.port=9000 "run 9000"
    

    So I just suggest to write shell script (or .bat in Windows) for easy starting with all required params.

    0 讨论(0)
  • 2021-01-05 10:16

    I just found a way to get the port no matter how the port is specified. Use the reverse route to get an Call object, and the use the absoluteUrl() method to get the absolute url of your action, which contains port. Code snippet:

    public class RouteController extends Controller {
    public  Promise<Result> getPortAction() {
        Call call = com.mycom.routes.RouteController.getPortAction();
        String absoluteUrl = call.absoluteURL(request());
        //Here absoluteUrl would be like http://localhost:9002/...., 9002 would be the port.
        ...
    } }
    
    0 讨论(0)
提交回复
热议问题