How to reverse generate an absolute URL from a rou

2019-02-02 15:14发布

问题:

I'd like to get the absolute URL from a controller in Play 2 Java. I found the exact same question for Scala, but I can't make it work in Java.

public class MyController extends Controller {
    public static Result myMethod() {
        return ok();
    }

    public static Result test() {
        Logger.info(routes.MyController.myMethod().url); // Doesn't work !
        Logger.info(routes.MyController.myMethod().absoluteURL()); // Doesn't work !
        Logger.info(routes.MyController.myMethod().absoluteURL(true)); // Doesn't work !
        return ok();
    }
}

Thanks for your help !

回答1:

Add request to absoluteURL()

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


回答2:

I'm not sure if this works in 2.0, but since you're using Java it might do the trick. I use it in 1.2.4.

Router.getFullUrl("Controller.action")

Good luck !

Edit : I import play.mvc.Router so if this doesn't exist in 2.0 you might find something similar.

Also, this is play's 2.0 documentation on routing, check Reverse routing, maybe it will help.

http://www.playframework.org/documentation/2.0.1/JavaRouting