How to pass array from jsp to servlet

I am trying to send some data from jsp to a servlet using an ajax call; In my java script, I have the following method:

function sendMessage(){
        var cellPhones=[];
        var title=$('#subject').val();
        var text=$('#smsText').val();
        var groupsName=$('#dg').datagrid('getSelections');
        for(var i=0;i<groupsName.length;i++){
            cellPhones.push(groupsName[i].cellphone);
        }
        alert(cellPhones);

        $.ajax({
            type:"POST",
            url:"<%=basePath%>/SendMsgServlet?flag=sendSms",
            data:{
                title:title,
                text:text,
                cellPhones:cellPhones
            }
        }).done(function(){
            alert("ok");
        })
    }

      

and in my doPost method I have:

if("sendSms".equals(flag.trim())){
        String title=request.getParameter("title");
        String text=request.getParameter("text");
        String[] cellPhones=request.getParameterValues("cellPhones");

        this.sendSms(title,text,cellPhones,request,response);
    }

      

The problem is cellPhones is null, nut is not null, can anyone help me?

+3
java javascript jsp servlets


source to share


4 answers


Try putting the JS array in some hidden element (as part of the html on the site) of the form that will be submitted to the servlet like:



var ele = document.createElement("input");
ele.setAttribute("hidden","");
ele.setAttribute("value",cellPhones.toString());

      

0


source to share


Why don't you create a class that will have an array as an attribute. set the field value and then set obj to query. This not only helps you with the servlet, but can also be used if you want to send some data back to your jsp.



0


source to share


In ajax, you send values ​​as an array like:

 url= "cellPhone[]=121212&cellPhone[]=121212&cellPhone[]=121212"

      

But in a servlet, you are trying to get the value as a single value. You need to get the values ​​as an array []

. Try,

String[] cellPhones=request.getParameterValues("cellPhones[]");
                                                          |- Use array sign

      

0


source to share


I solved the problem, all I had to do was convert mobiles to string, no hidden element needed. I just added this line of code:

var cellPhone=cellPhones.toString();

      

0


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics