Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing javascript array to servlet

I have looked previous questions on this topic on SO, but my problem is not solved yet.

I am passing the array from javascript to servlet.

JavaScript Code:

var action = new Array();
function getProtAcionValues(rowNo,columnCount)
{
    for(var j=0;j<columnCount;j++)
    {
        action[j] =  document.getElementById('textActions'+rowNo+''+j).value;
        alert(action[j]);
    }
}

Servlet Code:

String actions[] = request.getParameterValues("action[]");
if(actions!=null)
for(int i=0;i<actions.length;i++)
{
    System.out.print(" Action: "+actions);
}
else
    System.out.println("Action is null");

Using above code I am getting message "Action is null".

And if I try

String actions[] = request.getParameterNames("action[]");

I am getting Syntax error:

The method getParameterNames() in the type ServletRequest is not applicable for the arguments (String)

Please let me know if there is something wrong in code.

like image 255
Bhushan Avatar asked Dec 31 '12 08:12

Bhushan


People also ask

How to pass array from JavaScript to servlet?

Servlet Code: String actions[] = request. getParameterValues("action[]"); if(actions!= null) for(int i=0;i<actions.

How to pass array of objects from jsp to servlet?

This is an important distinction. However, if you want to pass data between web components like Servlets and JSPs, all during a common request-response cycle, you can stuff objects into the HttpSevletRequest scope using request. setAttribute and get it using request. getAttribute.


2 Answers

you can just simply get the array with the name of the array...

String actions[] = request.getParameterValues("action");

like image 128
Srinivas B Avatar answered Oct 22 '22 19:10

Srinivas B


You can't pass a java array as a parameter, as it is an structure. The best way is to serialize it into an string object like a jSon. You can use JSON.stringify. Simple and efficient. As you can serialize in the server also, it's very useful.

like image 31
zon7 Avatar answered Oct 22 '22 18:10

zon7