Repopulate ArrayList from JSP with Struts 2

你。 提交于 2019-11-27 16:24:30
Andrea Ligios

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.

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

Since it is a list of Questions Objects you are trying to populate a Question Object with a String. Please check if you have the converter defined to covert String into Question and also specified in the xwork-conversion.properties file

System.out.println(myQuestions); prints an empty list.

instead of doing this

private List<Question> myQuestions = new ArrayList<Question>();

do this

private List<Question> myQuestions;

When you are submiting the form, a new object of your Action class is created and your instance variable "myQuestions" gets reinitialized with each submission.

Hope this helps :)

When you submit the form Struts2 uses parameters named the same as field names. These parameters are populated to the action by the params interceptor which sets the values to the valueStack. Since the action is on top of the stack its properties will be set.

In your action you have an List<Question> but passing List<String>.

Built in Type Conversion Support:

collections - if not object type can be determined, it is assumed to be a String and a new ArrayList is created

To fix the problem use indexed property names like this

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!