Template to redirect to previous page after action

In my Play application, I have several actions (for example, β€œDelete” an object) that can be launched from different pages. After the action is launched, I would like to redirect the user to the page on which they were, before I performed the action. Is there a good sample that can be used for this on Play?

+8
redirect scala playframework
source share
3 answers

you can easily use @request.getHeader("referer") in your templates, for example, if you have a cancel button that should redirect you to the previous page, use this:

 <a href="@request.getHeader("referer")">Cancel</a> 

thus, you do not need to pass any additional information into your templates. (checked with game 2.3.4)

+4
source share

This is what I came up with in the end, although it is not particularly elegant, and I would be interested in how to do it. I added hidden input to my form with the current page url:

 @(implicit request: RequestHeader) ... <form action="@routes.Controller.doStuff()" method="post"> <input type="hidden" name="previousURL" value="@request.uri"/> ... </form> 

Then in my controller:

 def doStuff() = Action { implicit request => val previousURLOpt: Option[String] = for { requestMap <- request.body.asFormUrlEncoded values <- requestMap.get("previousURL") previousURL <- values.headOption } yield previousURL previousURLOpt match { case Some(previousURL) => Redirect(new Call("GET", previousURL)) case None => Redirect(routes.Controller.somewhereElse) } } 
+2
source share

The easiest way I found for this is from inside your controller method, use this:

 String refererUrl = request().getHeader("referer"); 

So you would do something like:

 public static Result query(String queryStr, int page, int offset) { String refererUrl = request().getHeader("referer"); Logger.info("refererUrl: " + refererUrl); if(queryStr.length() < 3) { flash(Application.FLASH_ERROR_KEY, "type a longer search than '" + queryStr.trim() + "'"); return redirect(refererUrl); } return ok(listings.render(searchService.searchListings(queryStr))); } 

Keep in mind that you need to do redirect () and NOT render () with the flash message.

+1
source share

All Articles