Skip to content
Advertisement

Struts2 – How to repopulate form having dynamically generated fieldnames (via expression) with submitted values after validation error

We have a Struts2 application where we are building survey feature using which application users will be able to create surveys by adding different questions.

These questions are comprised of question text and an html control for getting response.

The html controls so far supported are single and multi-select list, text field, textarea, checkbox and radiobox.

So the survey form renders displaying all questions added by the user where each question has its question text displayed followed by the html field control selected for that question.

Basically, it is a dynamic form where form field names are being dynamically generated as all surveys will be different and therefore there are no properties in the Action class backing survey form fields.

We are generating form field name using prefix question_ appended with database id of the question to represent each question response input field uniquely. Here is a snippet from our JSP page to make things clear.

JavaScript

On form submit, in the action class we are using HttpServletRequest to get submitted form field values. The way we identify which question the answer belongs to is through the request parameter name which as can be seen in the above JSP snippet starts with prefix ‘question_’ followed by question Id. So we split the parameter name to get the question id and associate value against that question.

The problem we are facing is with repopulating survey form with submitted values when the page is presented back to the user in case of validation error as the parameter names are dynamic and cannot be backed by properties defined in Action class.

I have tried to populate radio button and textarea fields using the below code and several other ways but to no avail

JavaScript

Below is the action mapping for survey submit action

JavaScript

Here is the code in Action class handling the submit logic:

JavaScript

Advertisement

Answer

We have finally solved the problem. The initial implementation was heading in a completely wrong direction but thanks to the clue from @RomanC, we re-factored the code and removed the direct use of HttpServletRequest to finally have a working solution. Core idea was to use a Bean for capturing response and have a List of those beans in the Action class corresponding to each survey question. On form submit, response is captured into the bean objects behind the scene by framework itself and thus available for further logic processing in submit handler action method.

Advertisement