预填充并重新显示 HTML 表单
创建表单的最佳非框架(仅限 JSP/Servlet)方法是什么,这样它可以:
- 预填充默认值/从数据库加载的数据
- 重新显示验证失败的提交值
执行其中一个或另一个似乎相当简单,但是创建一个同时支持这两者的表单是很棘手的。
例如,使用
${param.scheduledDate}
非常适合在验证失败时重新显示日期,但不能在页面加载时轻松地以编程方式设置。相反,
${myBean.scheduledDate}
它非常适合显示从数据库加载的值,但无法在验证失败时重新显示数据,因为 bean 使用的是 Date 类型的对象,而不是字符串。
我想到了一些事情,但似乎并不是那么好:
- 使用仅带有字符串的中间 bean
- 使用 servlet 过滤器在页面加载时设置参数
What is the best non-framework (JSP/Servlet only) way to create a form such that it can:
- Prepopulate with default values / data loaded from a database
- Redisplay submitted values which fail validation
It seems fairly straight forward to do one or the other, but creating a form that supports both simultaneously is tricky.
For example using
${param.scheduledDate}
works great for re-displaying a date on validation failure, but can't easily be set programmatically on page load. Conversely,
${myBean.scheduledDate}
works great for displaying values loaded from a database, but can't re-display data on validation failure since the bean is using an object of type Date, not string.
A few things come to mind, but non really seem all that good:
- use an intermediate bean with just strings
- use a servlet filter to set parameters on page load
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在视图一侧进行。在 EL 中使用条件运算符
?:
:请注意,我假设与 GET 不同,POST 请求在验证成功之前不会预填充
${bean}
。顺便说一句,这种冗长正是 MVC 框架存在的原因之一。例如,JSF 通过
EditableValueHolder
接口,由其他接口实现UIInput
组件。Do it in the view side. Use the conditional operator
?:
in EL:Note that I assume that unlike GET the POST request doesn't prepopulate the
${bean}
before validation has succeeded.This verboseness is by the way one of the reasons why MVC frameworks exist. JSF for example handles this fully transparently by the
EditableValueHolder
interface which is implemented by among othersUIInput
components.将 HTTP 请求转发回发布表单的同一页面违反了 Post-Redirect-Get< /a> 最佳实践,应该避免。可以保存用户在会话中提交的内容,或者使用 URL 参数来保存用户提交的值并重定向回原始页面,但这并不优雅。表单提交的最佳解决方案之一是使用 AJAX 来提交表单。
Forwarding the HTTP request back to the same page that posted the form violates the Post-Redirect-Get best practice and should be avoided. It is possible to save what the user submitted in the session or use URL parameters to save user submitted values and redirect back to the original page but that is not elegant. One of the best solutions for form submission is to use AJAX to submit the form.