Play Framework 2.1: Scala: how to get the whole base url (including protocol)?

做~自己de王妃 提交于 2019-12-05 01:17:43

Actually your portnumber will give you if it's http or https.

Start your Play server with https support JAVA_OPTS=-Dhttps.port=9001 play start

Here's a code snippet (you can make the validation more stable with a regex, take the https port number from properties ...)

def path = Action { request =>
    val path = 
      if(request.host.contains(":9000"))
        "http://" + request.host + "/some/path"
      else
        "https://" + request.host + "/some/path"
    Ok(path)
  }

The code will return

http://ServerIp:9000/some/path if it's thru http
https://ServerIp:9001/some/path if it's thru https

Actually there's a simple way to do it using Call class that reverse routers use to achieve similar thing. Given that you are within the scope of implicit request, you can do something like this:

new Call(request.method, input.request).absoluteURL()

and it will provide you with the complete url (protocol, host, route and parameters).

In Play 2.3 and later you can use the secure property of the Request class.

EECOLOR

I don't think there is.

A workaround is to use a protocol relative urls using //domain.com/path.

This however does not help you with links in email. In that case you could put the protocol in the application.conf. In most cases the difference is made because production supports https and development does not.

I have yet to find a situation where the above workarounds do not work.

My solution was to pass the beginning of the url as an additional parameter from javascript. The application.conf solution does not work for me, because the same application is accessible on http and https but from different subnet and domain.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!