难以理解路由优先级

Trouble with understanding routing priority

我正在建立某种讨论板,您可以在其中提出问题并写下答案。现在我 运行 陷入路由问题,似乎理解错误。

我有一个名为 index 的主页,您可以从那里单击一个按钮 "Ask question" 或另一个按钮 "Write Answer"。每个按钮都会指向另一个网页(askQuestion.scala.html 或 writeAnswer.scala.html),您可以在其中写下问题或答案。点击 submit 后,您将返回索引页面,新问题或答案将显示在该页面中。在后台,问题/答案被放入数据库中。

我的routes.conf:

# Home page
GET     /                           controllers.Application.index()

#Questions
GET     /FrageStellen               controllers.Application.askQuestion()
POST    /                           controllers.Application.sendQuestion()

#Answers
GET     /AntwortGeben               controllers.Application.writeAnswer()
POST    /                           controllers.Application.sendAnswer()

但是当我输入答案时,它会被写入数据库中的问题-table!这是因为问题路由在路由 table 中较高,因此它似乎首先被选中。

这违背了我对路由的理解,我认为路由由一个三元组组成:HTTP-Method, Request Path, Call definition ...并且由于调用定义不同(sendQuestion() 和 sendAnswer()),正确的一个应该被使用?

为什么不是这样?

我在 documentation of the play framework 中阅读了有关路由的信息并进行了谷歌搜索,但仍然不明白。

我也知道如何解决我的问题,但我想了解这里发生了什么。

修复 1: 改变这个

POST    /                           controllers.Application.sendAnswer()

至此

POST    /Antwort                    controllers.Application.sendAnswer()

缺点:这不再是主页(索引)。好像很奇怪。

修复 2: 编写一个将内容从表单发送到索引的组合方法。

缺点:我想将方法​​分开,以便在我的项目中保持更好的结构。此外,我还必须查看是否有人提出问题或编写答案,并基于此省略一个字段或使用另一个字段(答案有一个额外的问题 ID 字段 link 问题的答案)。

那么,为什么会在路由中发生这种情况,最好的处理方法是什么?

您应该 post 到具有不同请求路径的操作,然后重定向到 index.html。这是 Web 开发中推荐的方法。

http://en.wikipedia.org/wiki/Post/Redirect/Get

在 Play 中,每条路线都是路线方法 (GET/POST) 和路径(由静态部分和参数类型确定)的组合,因此如果您有两条路线具有相同的类型和路径只有第一个 是可解析的,其他的将被忽略,即使您使用其他名称的参数(但相同的参数类型)也是如此。

在这种情况下,bar(String bar) 方法 永远不会 被解析:

GET  /foo/:foo controllers.Application.foo(foo: String)
GET  /foo/:bar controllers.Application.bar(bar: String)

确保您不会混淆路线的最安全方法是始终成套使用唯一路径:

GET     /                 controllers.Application.index()

GET     /FrageStellen     controllers.Application.askQuestion()
POST    /FrageStellen     controllers.Application.sendQuestion()

GET     /AntwortGeben     controllers.Application.writeAnswer()
POST    /AntwortGeben     controllers.Application.sendAnswer()

最后,如果您想在 post 之后转到根页面,您可以 return 一个 redirect() 而不是 ok()