在我的 Play 应用程序中,我有几个可以从不同页面触发的操作(例如“删除”实体)。触发操作后,我想将用户重定向回他们在执行操作之前所在的页面。在 Play 中是否有一个很好的模式可以用于此?
问问题
2322 次
3 回答
5
您可以轻松地@request.getHeader("referer")
在模板中使用,例如,如果您有一个取消按钮应该将您重定向到上一页,请使用:
<a href="@request.getHeader("referer")">Cancel</a>
这样,您无需将任何额外信息传递给您的模板。(用 play 2.3.4 测试)
于 2014-12-29T21:47:06.407 回答
2
This is what I came up with in the end, although it isn't particularly elegant, and I'd be interested in better ways of doing it. I added a 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)
}
}
于 2013-07-02T08:15:25.983 回答
1
The easiest way I've found to do this, is from within your controller method, use this:
String refererUrl = request().getHeader("referer");
So, you'd 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 you need to do a redirect() and NOT a render() with a flash message.
于 2015-10-29T02:23:56.727 回答