Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to map javascript array in struts 2 action as List<String>

In an html page, I have checkboxes like following:

<input name="serviceareas" type="checkbox" id="cb1" value="1">
<input name="serviceareas" type="checkbox" id="cb2" value="2">
...

with the help of jquery I create javascript array of values for all the checked checkboxes

getSelectedValues : function() {
            var allVals = [];
            $('#checkboxTable :checked').each(function() {
                   allVals.push($(this).val());
              });
            //alert("allVals: "+allVals);

            return allVals;
        }

, and sends it to Struts 2 Action. For example in firebug request, I see :-

serviceareas 21,26,30

In the Action I have tried mapping it to

private List<String> serviceareas = new ArrayList<String>();

But instead SOP is printing it as an Object and it isn't able to cast it to java List

public class CreateEventAction extends ActionSupport {

    private List<String> serviceareas = new ArrayList<String>();

    public List<String> getServiceareas() {
        return serviceareas;
    }
    public void setServiceareas(List<String> serviceareas) {
        this.serviceareas = serviceareas;
    }

    @Override
    public String execute() throws Exception {

        if(this.serviceareas != null) {

                for (String serviceAreaId : this.serviceareas) {

                        System.out.println("String :"+serviceAreaId);

                }

            }

        return SUCCESS;
    }

Output: String :21,26,30

Please help. Thanks in advance.

like image 823
Amit Gill Avatar asked Sep 22 '26 13:09

Amit Gill


2 Answers

Assuming that you submit to action works, try to construct your parameters like that:

serviceareas=21&serviceareas=26&serviceareas=30
like image 77
Aleksandr M Avatar answered Sep 24 '26 05:09

Aleksandr M


Aleksandr M's answer should work. I am posting this answer just to make it more clear how to implement it.

Instead of submiting javascript array, submit a string.

getSelectedValues : function() {
    var allVals = '';
    $('#checkboxTable :checked').each(function() {
         allVals += "serviceareas="+$(this).val()+"&";  //prepare the string
    });
    if(allVals.length>0){
         allVals = allVals.substring(0,allVals.length-1); //remove last '&'
    }    
    return allVals; //submit this string as parameter
}
like image 40
Anupam Avatar answered Sep 24 '26 05:09

Anupam