简体   繁体   English

jsp中的多个Javascript标记包含

[英]Multiple Javascript tag inclusions in jsp

Here is my code in a jsp: 这是我在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>

Now please consider the following: 现在请考虑以下事项:

<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>

Both the codes give me the same output. 两个代码都给我相同的输出。
The question is which one is better when it comes to performance? 问题是哪一个在性能方面更好?
In the first case the script tag inside c:forEach repeats again and again. 在第一种情况下,c:forEach中的脚本标记一次又一次地重复。
But in the second case I'm creating one more c:forEach which is already present in the JSP. 但在第二种情况下,我正在创建一个c:forEach,它已经存在于JSP中。
Totally lost here. 完全迷失在这里。 Please advise. 请指教。

It's completely unnecessary to put those things in separate <script> tags. 将这些内容放在单独的<script>标记中是完全没有必要的。 If you really want to make it better, you should possibly be thinking of creating a JavaScript array literal instead of a series of "push()" calls. 如果你真的想让它变得更好,你应该考虑创建一个JavaScript数组文字,而不是一系列的“push()”调用。 A JSP extension to render a Java array as JSON would do the trick. 将Java数组呈现为JSON的JSP扩展可以解决这个问题。

edit — to elaborate, a JSON encoder made available as a JSTL function would allow you to write something like: 编辑 - 详细说明,作为JSTL函数提供的JSON编码器将允许您编写如下内容:

<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). “toJSON”函数将获取数组并将其呈现为标准JSON,具体取决于其内容(当然,根据所使用的JSON代码,这可能会受到一定限制)。 The resulting JavaScript delivered to the browser would look something like: 传递给浏览器的JavaScript结果如下所示:

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

again depending entirely on what's in the Java array. 再次完全取决于Java数组中的内容。 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). Java有各种JSON编码库,编写一个并不是很难(事实上,在特殊情况下,比调整开源库更容易 )。 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. 将函数作为JSTL EL函数提供是在某处创建公共静态函数并在.tld文件中声明它的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM