Spring MVC 验证 - 避免回发
我想验证 Spring 3 MVC 表单。当元素无效时,我想重新显示带有验证消息的表单。到目前为止这非常简单。问题是,当用户在无效提交后点击刷新时,我不希望他们发布,我希望他们获取。这意味着我需要从表单 POST(提交)进行重定向,以重新显示带有验证消息的表单(表单是通过 POST 提交的)。
我认为最好的方法是使用 SessionAttributeStore.retrieveAttribute 来测试表单是否已在用户会话中。如果是,则使用商店表单,否则创建一个新表单。
这听起来正确吗?有更好的方法吗?
I'd like to validate a Spring 3 MVC form. When an element is invalid, I want to re-display the form with a validation message. This is pretty simple so far. The rub is, when the user hits refresh after an invalid submission, I don't want them to POST, I want them to GET. This means I need to do a redirect from the form POST (submission) to re-display the form with validation messages (the form is submitted via a POST).
I'm thinking the best way to do this is to use SessionAttributeStore.retrieveAttribute to test if the form is already in the user's session. If it is, use the store form, otherwise create a new form.
Does this sound right? Is there a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了解决这个问题,我在 POST 重定向后将 Errors 对象存储在会话中。然后,在 GET 上,我将其放回模型中。这里有一些漏洞,但它应该在 99.999% 的情况下都能工作。
To solve this problem, I store the Errors object in the session after a redirect on a POST. Then, on a GET, I put it back in the model. There are some holes here, but it should work 99.999% of the time.
您的问题尚不清楚,但听起来您的 GET 和 POST 操作已映射到同一处理程序。在这种情况下,您可以执行以下操作:
在 JSP 中检查表单上是否有任何错误并根据需要进行显示。
It's not clear from your question but it sounds like your GET and POST actions are mapped to the same handler. In that case you can do something like:
In the JSP check if there are any error on the form and display as needed.
这种方法称为 PRG (POST/REdirect/GET) 设计模式,几天前我将其解释为答案之一:
Spring MVC 简单重定向控制器示例
希望有帮助:)
Such approach is called PRG (POST/REdirect/GET) design pattern I explained it few days ago as one of the answers:
Spring MVC Simple Redirect Controller Example
Hope it helps :)