Ryan
Ryan

Reputation: 7951

Prepopulate AND redisplay an HTML Form

What is the best non-framework (JSP/Servlet only) way to create a form such that it can:

  1. Prepopulate with default values / data loaded from a database
  2. 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:

Upvotes: 2

Views: 1991

Answers (2)

Ryan
Ryan

Reputation: 7951

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.

Upvotes: 0

BalusC
BalusC

Reputation: 1108537

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)}" />

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 others UIInput components.

Upvotes: 3

Related Questions