如何使用jsp将java数组传输到javaScript数组? [英] How to transfer java array to javaScript array using jsp?

查看:94
本文介绍了如何使用jsp将java数组传输到javaScript数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务器上有一个字符串列表,我试图以数组的形式访问客户端.我尝试使用的代码如下:

I have a list of strings on my server which I am trying to get to the client in the form of an array. The code I am attempting to use is the following:

在jsp中我有一个List

我正在尝试以下代码:

<%int j = 0; %>
for(var i = 0; i < <%=columns.size()%>; i++)
{
  colArray[i] = "<%=columns.get(j++)%>";
}

此代码只是为 colArray 中的每个元素返回列列表中的第一个元素.

This code simply returns the first element in the columns list for every element in the colArray.

我也试过:

colArray = <%=columns.toArray()%>;

这也不起作用.我觉得我在某个地方犯了一个小错误,只是没有看到.我正在尝试做的事情是否可能以我正在尝试的方式进行?

which does not work either. I feel like I am making a little mistake somewhere and am just not seeing it. Is what I am trying to do possible in the way that I am attempting?

谢谢.

推荐答案

您将在服务器上执行的 JSP 代码与在客户端执行的 JavaScript 代码混合在一起.片段 <%=columns.get(j++)%> 在服务器上执行一次,此时围绕它的 JavaScript 循环无关紧要.当它到达客户端时,循环的主体只是说 colArray[i] = "first entry"; 这当然会将相同的字符串放入数组的每个元素中.

You're getting the JSP code that is executed on the server mixed up with the JavaScript code that's executed on the client. The snippet <%=columns.get(j++)%> is executed once, on the server, and the JavaScript loop around it is irrelevant at this point. When it arrives the the client, the loop's body just says colArray[i] = "first entry"; which of course puts the same string into every element of the array.

您需要做的是在服务器上执行一个循环,如下所示:

What you need to do instead is to have a loop execute on the server, like this:

<% for (int i=0; i<columns.size(); i++) { %>
colArray[<%= i %>] = "<%= columns.get(i) %>"; 
<% } %>

我的 JSP 技能生疏了,语法可能会有所不同,但我希望你能明白.

My JSP skills are rusty, and the syntax may be different, but I hope you get the idea.

正如评论中指出的那样,您需要非常小心地转义这些字符串中可能导致它们被解释为 JavaScript 代码的任何内容(最突出的引号)——尤其是如果它们包含用户生成的内容.否则,您的应用就会对跨站脚本跨站请求伪造 攻击.

As was pointed out in the comments, you need to be VERY careful about escaping anything in those Strings that could cause them to be interpreted as JavaScript code (most prominently quotation marks) - especially if they contain user-generated content. Otherwise you're leaving your app wide open to Cross-site scripting and Cross-site request forgery attacks.

这篇关于如何使用jsp将java数组传输到javaScript数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆