问题描述
创建表单以使其可以做到的最好的非框架(仅JSP/Servlet)方法是什么:
What is the best non-framework (JSP/Servlet only) way to create a form such that it can:
- 使用默认值/从数据库加载的数据进行预填充
- 重新显示未通过验证的提交值
做一个或另一个似乎很简单,但是创建一个同时支持两者的表单是很棘手的.
It seems fairly straight forward to do one or the other, but creating a form that supports both simultaneously is tricky.
例如使用
${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}
对于显示从数据库加载的值非常有用,但是由于bean使用的是Date类型的对象,而不是字符串,因此在验证失败时无法重新显示数据.
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:
- 使用仅包含字符串的中间bean
- 使用servlet过滤器设置页面加载时的参数
推荐答案
在视图侧进行操作.在EL中使用条件运算符?:
Do it in the view side. Use the conditional operator ?:
in EL:
<input name="foo" value="${fn:escapeXml(empty bean.foo ? param.foo : bean.foo)}" />
请注意,我认为与GET不同,POST请求不会在验证成功之前预先填充${bean}
.
Note that I assume that unlike GET the POST request doesn't prepopulate the ${bean}
before validation has succeeded.
这种冗长的方式是MVC框架存在的原因之一.例如, JSF 通过 EditableValueHolder
接口,该接口由其他 UIInput
组件.
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 others UIInput
components.
这篇关于预填充并重新显示HTML表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!