Monday, February 11, 2013

Clicking on submit twice while submitting a form in JSF

Assuming the reader of this post has considerate amount of knowledge in JSF (Java Server Faces) Framework.

This peculiar problem occurs while developing web application using JSF Framework. It is really very annoying and makes your application look very dumb and childish. I had got stuck with this problem and finally found out the root cause and solution which i would like to share with fellow programmers.
Suppose, you have a JSF web page which has a form and this form contains SelectOneMenu elements which has ValueChangeListener methods. When, you click on submit button first time, form doesn't get submitted, same page reloads. Second time, when you click on submit button, form submits. This was my case and after digging deep into it, I found that form was getting submitted and it was executing the method specified in action attribute of command button. But, my logic inside that method was returning a value which didn't allow the navigation of page to next page. Reason for the failure of my logic was value of bean property was not getting updated during first submit. I had a checkbox which was checked when clicking on submit, so the corresponding bean value was supposed to be true instead it was false. Bean is not getting updated with proper values when you click on submit first time. This happens due to Value Change Event Listeners.

For a form to submit properly. The same datamodel should be preseved in the subsequent request as it was during initial display. When the page first loads, properties in bean will have some default or null values. SelectOneMenu element in your form will populate a different value to the bean after its loaded and thus same datamodel is not preserved. Since ValueChangeListener methods are registered, it will not update the bean with proper values and there will be problems in form submission. To preserve same datamodel, you can initialize all bean properties to a default value in bean constructor. This resolves the issue.

Other than this, if you have nested form tags also, this problem occurs.