0

这是我在jsp中的代码:

<script>  
var myArray = [];
</script>
    <c:forEach var="attributes" items="FROMthisBEAN"  varStatus="vStatus" >  
                <script>
                 //Executes for each iteration. Do something COOL.
                 myArray.push("Something from this iteration");
                </script>
    </c:forEach>

现在请考虑以下几点:

<script>  
    var myArray = [];    
        <c:forEach var="attributes" items="FROMthisBEAN"  varStatus="vStatus" >  
                    myArray.push("Something from this iteration");
        </c:forEach>
 </script>
<c:forEach var="attributes" items="FROMthisBEAN"  varStatus="vStatus" >  
                //Executes for each iteration. Do something COOL.
</c:forEach>

两个代码都给了我相同的输出。
问题是在性能方面哪个更好?
在第一种情况下,c:forEach 中的脚本标签会一次又一次地重复。
但在第二种情况下,我正在创建一个已经存在于 JSP 中的 c:forEach。
完全迷失在这里。请指教。

4

1 回答 1

2

完全没有必要将这些东西放在单独的<script>标签中。如果你真的想让它变得更好,你可能应该考虑创建一个 JavaScript 数组字面量,而不是一系列“push()”调用。将 Java 数组呈现为 JSON 的 JSP 扩展就可以解决问题。

edit — to elaborate, a JSON encoder made available as a JSTL function would allow you to write something like:

<script>
  var myArray = ${yourTLD:toJSON( some.java.array _)};
</script>

The "toJSON" function would take the array and render it as standard JSON, depending on its contents (and of course that'd probably be somewhat constrained, depending on the JSON code used). The resulting JavaScript delivered to the browser would look something like:

<script>
  var myArray = [ "something", "something", "something" ];
</script>

again depending entirely on what's in the Java array. There are various JSON encoding libraries for Java, and it's not terribly hard to write one (and in fact that can be easier in special cases than adapting an open source library). Providing the function as a JSTL EL function is a matter of creating a public static function somewhere and declaring it in your .tld file.

于 2012-05-23T14:44:58.597 回答