1

我有一个HashSet字符串,它是用以下代码制作的:

Set<String> scripts = new HashSet<>();
String contextPath = request.getContextPath();
scripts.add(contextPath + "/resources/scripts/jquery.cycle2.js");
scripts.add(contextPath + "/resources/scripts/jquery.cycle2.center.js");
scripts.add(contextPath + "/resources/scripts/slideshow.js");
request.setAttribute("scripts", scripts);

现在在一个 JSP 页面中,使用 JSTL,我执行了一个普通的 forEach 循环:

<c:if test="${not empty scripts}">
    <c:forEach var="script" items="${scripts}" >
        <script type="text/javascript"
                src="${script}">
                          </script> 
    </c:forEach>
</c:if>

加载页面时,这会导致:

<script type="text/javascript"
        src="[/InfoKiosk/resources/scripts/jquery.cycle2.center.js">
                          </script> 

<script type="text/javascript"
        src=" /InfoKiosk/resources/scripts/jquery.cycle2.js">
                          </script> 

<script type="text/javascript"
        src=" /InfoKiosk/resources/scripts/slideshow.js]">
                          </script> 

请注意出现在第一个脚本源之前和最后一个之后的方括号([和)。]他们来自哪里?

4

2 回答 2

2

出于某种原因,它正在调用toString()你的集合。然后,这会将您的集合变为[script1, script2, script3],调用foreach此字符串拆分逗号,创建我们看到的效果。

当我替换为时,我可以准确地看到您所看到
request.setAttribute("scripts", scripts);

request.setAttribute("scripts", scripts.toString());

如果没有这个,我无法重现你所看到的,但是我正在运行 java 6。

不是答案,而是我希望的有用见解!

于 2012-12-18T14:23:09.050 回答
0

The problem occured because the scripts variable was set in a JSP through an attribute for a custom tag, like this:

<t:genericpage scripts="${scripts}">
....

Of course, this converted the collection to a string by calling its toString() method. We have solved it in a different way, by setting the request attribute in the servlet.

于 2012-12-19T17:32:51.920 回答