Search code examples
javalistjspstruts2ognl

Repopulate ArrayList from JSP with Struts 2


This is the form I am using to repopulate the ArrayList

<form method = "POST" action = "addItemsToTemplate">
    <s:iterator value = "myQuestions" var = "quizItem"  status="key">
        <s:textfield name = "quizItem.question"/> 
    </s:iterator>
    <input type = "submit" value = "submit"/>
</form>

This is the action class

public class QuizTest extends ActionSupport{



    public String execute(){

            List<Question>  q=  myQuestions;
            System.out.println(myQuestions);

            return "success";
        }


   public String populateQuestions(){
             //more code here
   }

    public void setMyQuestions(List<Question> myQuestions) {
        this.myQuestions = myQuestions;
    }
    private List<Question> myQuestions = new ArrayList<Question>();

}

Where myQuestions is a List of Question Objects. upon submission this gives me an error

Unexpected Exception caught setting 'quizItem.question' on 'class quiz.actions.QuizTemplateAction: Error setting expression 'quizItem.question' with value '[Ljava.lang.String;@1b3409f'

and System.out.println(myQuestions); prints an empty list. but the myQuestions was already been populated from another by this method populateQuestions(), before submitting the form


Solution

  • Unexpected Exception caught setting 'quizItem.question' on 'class quiz.actions.QuizTemplateAction: Error setting expression 'quizItem.question' with value '[Ljava.lang.String;@1b3409f'

    You are trying to send all the questions (attribute) descriptions into the first Question (object) as a List<String>, because you are not specifying the index (as you correctly do with <s:property/> in your other questions... ?!).

    Change this

    <s:textfield name = "quizItem.question"/> 
    

    To this

    <s:textfield name = "quizItem[%{#key.index}].question"/>
    

    To send a single String to each correspondent Question object, instead of a List<String> to the first Question object.