0

I want to access the jsp array in Javascript. How it is possible?

JSpCode

<%!
String s[];
%>

<%
List l=(List)request.getAttribute("listResource");
System.out.println("The Elements In List::"+l);

if(l!=null)
{
    System.out.println("The Size of List::"+l.size());
    int siz=l.size();
    Iterator itr=l.iterator();
    while(itr.hasNext())
    {
        s=new String[siz];
        int i=0;
        s[i]=itr.next().toString();
        System.out.println("The Elments are:"+s[i]);
        i++;
    }
}
%>

JavaScriptCode

function verify_details()
{
    var resourceId=document.getElementById("res").value;
    var rid=new Array();
    rid=<%=s%>
    alert(rid[0]);  

}

I tried like this but I am not getting the values.

cweiske
  • 30,033
  • 14
  • 133
  • 194
  • 2
    Any chance that you can indent the code properly so that others have a slight change to read it? – Felix Kling Jul 02 '11 at 08:59
  • possible duplicate of [Populating JavaScript Array from JSP List](http://stackoverflow.com/questions/3040645/populating-javascript-array-from-jsp-list) – Felix Kling Jul 02 '11 at 09:01
  • Not sure what any of this is, but you're only setting the first element of `s`. Probably should move the declaration of `i` to outside the loop. – YXD Jul 02 '11 at 09:06

1 Answers1

2

JSP code is executed at server side, and generates text. Some of this text happens to be JavaScript code. JavaScript code is executed at client side, where the Java array doesn't exist anymore as a data structure.

When you write

rid=<%=s%>

You're asking to generate the following String : "rid=" + s.toString()

s being a String array, the generated Javascript code will thus look like this :

rid=[Ljava.lang.String;@1242719c

And this is obviously not valid JavaScript code.

JavaScript code, when you're generating it with a JSP, is not any different from HTML code. If you want to generate the code rid = ['a', 'b', 'c']; from a String Java array containing "a", "b" and "c", you need to iterate through the Java array and output a single quote followed by the current String followed by a single quote followed by a comma. Additionnally, you should escape each string to transform a quote character into \', a newline character into \n, etc. Use StringEscapeUtils.escapeJavaScript from commons-lang to do that.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255