Is there a quick built in way to forward a request in the scala Play framework
Asked Answered
M

1

6

I'm looking for something like

def proxy = Action.async { implicit req =>
  //do something with req
  val newRequest = req.map( r = r.path = "http://newurl");
  forward(newRequest)
}

I saw that there is a redirect method but that only allows me to pass the request parameters and not everything else, headers, etc.

I am hoping there is something built in so I don't have to build it myself.

Macro answered 23/4, 2015 at 16:45 Comment(8)
ah sorry I updated it. I want to forward it to a new url but with everything else in the request the sameMacro
Is the other url being served by the same play instance, or is it remote?Liturgical
What about Redirect? Browser will send all cookies and headers, you can specify url from reverse routing with new parameters. It will not work for other requests then GETNarcosis
@AndrzejJozwik Does Redirect forward all cookies and headers? I wasn't sure it did and thats why I was avoiding it.Macro
Redirect is not supposed to keep cookies and headers. If you want to forward the request processing to another component/function of your Play app, you should look at Action composition.Unseen
@Macro - you can always add/remove headers, cookies: Redirect(route.Controller.pageToRedirect(param1,param2)).withCookies( Cookie("theme", "blue") ).withHeaders(CACHE_CONTROL -> "max-age=3600", ETAG -> "xx")Narcosis
@Macro assumig that you perform the request from the browser and while you don't modify your cookies and or headers within your proxy action in next request they will be exactly the same. Use some debbuging to validate this.Snotty
Nice, I'll go with Redirect thenMacro
H
-1

I'm not sure if this meets your requirements, but have you had a look into Play's WS.

The action forwardTo gets an url, fetches the according page and returns it as this request's response. It's not exactly like an forward in the Spring framework but it does the job for me.

/**
 * Like an internal redirect or an proxy. The URL in the browser doesn't
 * change.
 */
public Promise<Result> forwardTo(String url) {
    Promise<WS.Response> response = WS.url(url).get();
    return response.map(new Function<WS.Response, Result>() {
        public Result apply(WS.Response response) {
            // Prevent browser from caching pages - this would be an
            // security issue
            response().setHeader("Cache-control", "no-cache, no-store");
            return ok(response.getBody()).as("text/html");
        }
    });
}

(I'm using Play 2.2.3)

Hawk answered 24/4, 2015 at 10:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.