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

无人久伴 提交于 2019-12-22 02:03:54

问题


Currently I am able to get the host from the request, which includes domain and optional port. Unfortunately, it does not include the protocol (http vs https), so I cannot create absolute urls to the site itself.

object Application extends Controller {
  def index = Action { request =>
    Ok(request.host + "/some/path") // Returns "localhost:9000/some/path"
  }
}

Is there any way to get the protocol from the request object?


回答1:


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



回答2:


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).




回答3:


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




回答4:


I don't think there is.

  • Play Framework 2.0 itself does not support https, see: play-framework [2.0] HTTPS
  • The implementation of absoluteURL method of the Call class of the Play Framework 2.0 does not suggest it.

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.




回答5:


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.



来源:https://stackoverflow.com/questions/14863553/play-framework-2-1-scala-how-to-get-the-whole-base-url-including-protocol

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