Redirect with Bad Request Status

佐手、 提交于 2019-12-11 14:16:19

问题


I'm using Play Framework v2.2.2 (scala) and trying to do a Redirect with a 400 (Bad Request) status.

Currently I'm doing redirects using reverse routing like so:

Redirect(Games.Controllers.routes.SportViewController.show)

I'd like to be able to specify the status of the redirect. I tried adding an additional argument to the call, but I get a compile error of:

Overloaded method value [Redirect] cannot be applied to (play.api.mvc.Call, Int)

In the documentation I noticed you can specify a string uri with a redirect status, however, I would really like to continue using reverse routing in my code instead of having string uri values all over the place.

Redirect("redirect/path", status = 400)

Any ideas or suggestions as how I can accomplish a Bad Request (400) redirect using reverse routing? Is there something I missed in the documentation? Is there a completely different/better way of doing this?

Thanks a bunch!


EDIT

To give a bit more context as to why I asked about the redirect with a specific status. I'm processing a form post. On a successful post (eg. user posted data is valid), then redirect to route X, and on unsuccessful post (eg. user data is missing or invalid), then redirect to route Y. On unsuccessful posts, what status code should be used?


回答1:


This is the signature of the Redirect you're interested in (minus the changed status):

def Redirect(call: Call): SimpleResult = Redirect(call.url) 

It simply calls another overload that does the leg work:

def Redirect(url: String, queryString: Map[String, Seq[String]] = Map.empty, status: Int = SEE_OTHER)

So we could easily create our own overload that calls the one above with our own controller:

def Redirect(call: Call, status: Int): SimpleResult = Redirect(call.url, Map.empty, status)



回答2:


The Redirect action should be used for 3XX redirects as defined in the HTTP specification http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html .

When the Redirect action is called it will set a Location header (see 14.30 Location) as well as a 3xx status header. A browser will attempt to load the URI from location header as a new request and so will use the HTTP status code of the final destination.

Redirects should only be used for

  • At the end of a successful form post to prevent duplicate submissions on refresh / back button
  • A piece of content has moved and no longer available at the old URI

If you want to explicitly give a 400 error you need to use the BadRequest action and serve the error page from your app.

def badAction = BadRequest {
  views.html.myError
}

Or if you want to redirect to a external page keep the existing default 3XX status



来源:https://stackoverflow.com/questions/24128526/redirect-with-bad-request-status

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!