Forma dinámica en Spring 3

I have custom Question objects which I render into html form elements. I want to be able to dynamically create these objects and generate a dynamic html form from them. The question object has a String property to hold the result from the form. How can I get this to work in Spring?

The way I have it working (which doesn't seem ideal), is I have a bean to back the custom form. This bean has two properties: a List to hold the questions to be displayed and a List to hold the results. The JSP has a tag which tells it to use the bean as a model attribute. Then I have a custom JSP tag that takes the List and renders them into form elements. The elements are given IDs of answer[n] and Spring will put the results of the form into the List property in the backing bean.

Does anyone know how I can do this better?

preguntado el 08 de enero de 11 a las 20:01

This seems similar to my old question… -

It does. Why didn't you select an answer? -

[Here][1] is the solution I implemented. [1]:… -

1 Respuestas

My problem was a lack of experience.

I ended up with this (much simplified for explanation):

My bean has the following fields: String questionType, String questionText, String answer. My list of beans is List questions.

When I generate the HTML from the list of beans, I just need to make the id/name of each form element match up with the name of the list, and the position of the bean within the list.

So, if my list of questions looks like this:

[0] {questionType="TEXT", questionText="What is your name?", answerText=null}
[1] {questionType="TEXT", questionText="What is your quest?", answerText=null}
[2] {questionType="TEXT", questionText="What is your favorite color?", answerText=null}

Then I need to generate the following HTML when I loop through the list:

<div class="question">
    <p class="questionText">What is your name?</p>
    <input type="text" id="questions[0].answerText" name="questions[0].answerText" />
<div class="question">
    <p class="questionText">What is your quest?</p>
    <input type="text" id="questions[1].answerText" name="questions[1].answerText" />
<div class="question">
    <p class="questionText">What is your favorite color?</p>
    <input type="text" id="questions[2].answerText" name="questions[2].answerText" />

When the form is submitted, Spring will find those beans and call setAnswerText(String value) on them with the form data.

I hope this helps someone else stumbling at the beginning of their Spring MVC journey.

Respondido 01 Abr '11, 19:04

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.