如何在< script>中访问用户定义对象的数组在JSP? [英] How to access array of user defined objects within <script> in JSP?
问题描述
我有一组用户定义的对象,我从servlet传递给JSP。现在,我需要在JSP中的脚本标记内访问此数组。我该怎么办?
I have an array of user defined objects which I'm passing from a servlet to a JSP. Now, I need to access this array within the script tag in my JSP. How do I do it?
现在,我在脚本标签中有以下内容:
For now, I have the following within script tag:
var dCount = '${chart}';
var index;
for(index=0; index<dCount.length;index++){
alert(dCount);
}
当我这样做时,我将输出视为未定义。我认为这是因为 $ {chart}
返回一个对象?如果是这样,我该如何将其转换为用户定义的类?或者这里有其他问题吗?
When I do this, I get the output as undefined. I assume this is bcause the ${chart}
returns an Object? If so, how do I convert it to my user defined class? Or is something else the problem here?
谢谢。
推荐答案
您需要意识到JSP基本上是一个HTML代码生成器,而CSS / JS是生成的HTML输出的一部分。您需要以生成有效HTML / JS代码的方式编写JSP代码。一个有3个对象的有效JS数组,每个属性 foo
和 bar
看起来像这样:
You need to realize that JSP is basically a HTML code generator and that CSS/JS is part of the generated HTML output. You need to write JSP code in such way that valid HTML/JS code is generated. A valid JS array of 3 objects with each the properties foo
and bar
look like this:
var chart = [{
foo: "foo1",
bar: "bar1"
},{
foo: "foo2",
bar: "bar2"
},{
foo: "foo3",
bar: "bar3"
}];
var index;
for(index = 0; index < chart.length; index++) {
var item = chart[index];
alert(item.foo + ", " + item.bar);
}
现在,您需要确保以这样的方式编写JSP代码: 完全生成此有效的HTML / JS代码(您可以通过右键单击并在webbrowser中查看源进行验证)。
Now, you need to make sure that you write JSP code in such way that exactly this valid HTML/JS code is generated (as you can verify by rightclick and View Source in webbrowser).
如果 $ {chart}
是列表< Item>
或 Item []
,最天真的方法之一是使用< c:forEach>
来循环它,打印所需的JS代码输出:
Provided that ${chart}
is a List<Item>
or Item[]
, one of most naive ways is using <c:forEach>
to loop over it, printing the desired JS code output:
var chart = [<c:forEach items="${chart}" var="item" varStatus="loop">
{ foo: "${item.foo}", bar: "${item.bar}" }${loop.last ? '' : ','}
</c:forEach>];
最简单的形式,它应该可以正常工作。但是,一旦你将特殊字符作为属性值,例如甚至换行符,就会出现麻烦。你需要逃避它。更好的是使用现有的 JSON库,例如 Google Gson 为了转换复杂的Java对象,例如
列表< Item>
或项目[]
,到一个有效的JSON字符串。例如,在servlet中如下:
In its simplest form, it should work fine. However, trouble starts once you get "special characters" as property values, such as "
or even a newline. You'd need to escape it. Much better is to use an existing JSON library, such as Google Gson in order to convert a complex Java object, such as a List<Item>
or Item[]
, to a valid JSON string. E.g. as follows in the servlet:
List<Item> chart = createItSomehow();
request.setAttribute("chart", new Gson().toJson(chart));
// ...
然后你可以这样做:
var chart = ${chart};
这篇关于如何在< script>中访问用户定义对象的数组在JSP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!