Search code examples
jspstruts2struts-action

Struts2 - passing data from jsp form fields with same name to action class


In my struts form I have couple of fields (textfields) with the same name. They all carry the same information (through js change event). However, in the action class, they are imported as comma separated values instead of the value once.

Here is a snippet from item.jsp:

<s:select label="Part of speech" key='item.pos' list=.../>
<div class="verb"><s:textfield key='item.subitem.root'/></div>
<!-- hidden if item.pos!=verb -->
.
.
.
<div class="noun"><s:textfield key='item.subitem.root'/></div>
<!-- hidden if item.pos!=noun -->

The above textfield appears several times and is shown or hidden according to the part of speech. All the textfields have same key(or name) since they all point to the same field in the object 'item'. With JS function, they all have the same value inside.

My problem is:
When the string from the jsp is passed to the action class, the resulting 'root' field in the 'subitem' of the 'item' has all values comma separated. That is, suppose I input 'xxx' as the root, item.getSubitem().getRoot() will result in: 'xxx,xxx,xxx,xxx,xxx,xxx'.
If I skip the JS function which unifies all the values, it will result in: ',,xxx,,,'.

Any ideas how to solve this matter?


Solution

  • Using fields with same name needs some considerations:

    If all fields have same value, means you need only one of them to be sent to server, you may consider to rename other fields, or you can make other redundant fields disabled. Disabling an input or input hidden , will prevent the browser to send it.

    If you need to have the value of all fields(inputs) at your server, you need to define a index property simple as below:

        private String[] root;
    
        public String[] getRoot() {
            return root;
        }
    
        public void setRoot(String[] root) {
            this.root = root;
        }