afxdesign
afxdesign

Reputation: 453

How to get absolute route url as String In Play framework 2?

I am currently getting a relative url route as a String via:

String url = controllers.directory.routes.Directory.viewOrganisation( org.id ).url();

This works fine however I would like to get the full absolute url. I am sure this is simple, I just can't seem to find it.

Alternatively, how can I get the current domain within a view to add to the relative url?

Upvotes: 23

Views: 16868

Answers (2)

kuonirat
kuonirat

Reputation: 313

For Scala programmer: in Play 2.2.x the absoluteURL is overloaded in this way:

def absoluteURL(secure: Boolean = false)(implicit request: RequestHeader): String

So if you write just

routes.MyController.myMethod().absoluteURL(request)

you'll get an error:

Overloaded method value [absoluteURL] cannot be applied to (play.api.mvc.Request[play.api.mvc.AnyContent])

There are two options. You either declare the request as implicit:

def myMethod() = Action { implicit request =>
    ...
}

and get rid of the parameters entirely (you can do it, because the other has a default value):

routes.MyController.myMethod().absoluteURL()

or you have to specify both parameters explicitly.

I'm writing this answer here, because the question is "How to get absolute route url as String In Play framework 2" and the accepted answer is for Java only. The Scala version has it's nuances.

Upvotes: 8

biesior
biesior

Reputation: 55798

Indeed it is simple and it was also answered on the Stack

Follow this question: How to reverse generate an absolute URL from a route on Play 2 Java?

In very general you need:

routes.MyController.myMethod().absoluteURL(request());

Upvotes: 24

Related Questions