简体   繁体   中英

Array literals in JSP Expression Language?

I've been able to do Array literals in Thymeleaf's expression language before (using...OGNL?...I think...). Now I am using Spring/JSP. Do the JSP or Spring Expression Languages support Array Literals? I can't find any reference to them.

UPDATE: This is basically what I'm trying to do:

<c:set var="myUrls" value="${new String[] {
    mk:getUrl(),
    mk:getOtherUrl(),
    mk:getDifferentUrl()
}}" />

You could hack it together in a scriptlet-less way with a little help of maps, <jsp:useBean> and EL 2.2.

<jsp:useBean id="map" class="java.util.LinkedHashMap" />
<c:set target="${map}" property="url" value="${mk.url}" />
<c:set target="${map}" property="otherUrl" value="${mk.otherUrl}" />
<c:set target="${map}" property="differentUrl" value="${mk.differentUrl}" />
<c:set var="array" value="${map.values().toArray()}" />

<c:forEach items="${array}" var="item">
    ${item}<br/>
</c:forEach>

If your environment doesn't support EL 2.2, just stick to map and access it via the map.

<c:forEach items="${map}" var="entry">
    ${entry.value}<br/>
</c:forEach>

Noted should be that your underlying problem is bigger. You shouldn't be manipulating the model directly in the view. The controller is responsible for that. You should be altering the model in such way so that it's exactly what the view expects. Eg by adding a property, or by letting the controller do the job.

You can use scriptlet to use vanilla Java, in JSP1.x with <% /* Java */ %> block, in JSP2 with something like:

<jsp:scriptlet><![CDATA[
pageContext.setAttribute("myArray", new String[] { "a", "b", "c" });
]]></jsp:scriptlet>

<!-- so then ... -->
${myArray} <!-- or ... -->
<c:forEach items="${myArray}" var="str">
  <p>${str}</p>
</c:forEach>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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