Teach and redraw the HTML form

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

  • Assume default values ​​/ data loaded from database
  • Retry values ​​that are not checked

It seems pretty straightforward to do one or the other, but creating a form that supports both at the same time is a daunting task.

For example, using

${param.scheduledDate} 

great for re-displaying a date with a validation error, but cannot be easily set programmatically when the page loads. On the other hand,

 ${myBean.scheduledDate} 

works great for displaying values ​​loaded from the database, but cannot re-display data when validation fails, since the bean uses an object of type Date rather than a string.

A few things come to mind, but in fact all this is not so good:

  • use intermediate bean with strings only
  • use a servlet filter to set parameters when loading a page
+1
source share
2 answers

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 does not prevail ${bean} before the check is completed.

This verbosity, by the way, is one of the reasons for the existence of MVC frameworks. JSF , for example, fully transparently handles the EditableValueHolder interface, which is implemented among other UIInput components.

+2
source

Redirecting an HTTP request to the same page on which the form is posted violates Post-Redirect-Get best practice and should be avoided. You can save what the user presented in the session or use the URL parameters to save the values ​​entered by the user and redirect back to the original page, but this is not elegant. One of the best solutions for submitting a form is to use AJAX to submit the form.

0
source

Source: https://habr.com/ru/post/1340151/


All Articles