Note that there are some explanatory texts on larger screens.

plurals
  1. POGet the class name of an array in JSTL
    primarykey
    data
    text
    <p>I'm trying to build a url in a JSP from a <code>Map&lt;String, Object&gt;</code> of parameters. The existing code iterates through the map and adds c:params for the keys and values: </p> <pre><code>&lt;c:url value="/"&gt; &lt;c:forEach items="${myParamMap}" var="parameter"&gt; &lt;c:param name="${parameter.key}" value="${parameter.value}" /&gt; &lt;/c:forEach&gt; &lt;/c:url&gt; </code></pre> <p>I've run into the case where the value of an entry in the map is actually an array of Objects. My next attempt was to add a nested loop to iterate over the values as necessary:</p> <pre><code>&lt;c:url value="/"&gt; &lt;c:forEach items="${myParamMap}" var="parameter"&gt; &lt;c:forEach items="${parameter.value}" var="innerValue"&gt; &lt;c:param name="${parameter.key}" value="${innerValue}" /&gt; &lt;/c:forEach&gt; &lt;/c:forEach&gt; &lt;/c:url&gt; </code></pre> <p>But of course this breaks the normal situation where the value is not iterable. </p> <p>My next idea was to check whether the value is an array via some kind of "instanceof" check. The only way I could find on the internet to do this was: <code>${object.class.className == 'Whatever'}</code>. </p> <p>This does not work for arrays in JSTL because for the expression <code>${someArray.class}</code>, JSTL tries to convert the <code>.class</code> part into an integer in order to use it as an index (I can't believe someone thought this was a good idea).</p> <p>My next move is to use scriptlets but I'm still curious to see if there's a way to do this with pure JSTL.</p> <hr> <p>Using scriptlets is the way to go in this case. I ended up with something like:</p> <pre><code>&lt;c:set var="val" value="${parameter.value}"&gt; &lt;% boolean isArray = pageContext.getAttribute("val").getClass().isArray(); %&gt; &lt;c:choose&gt; &lt;c:when test="&lt;%= isArray &gt;"&gt; ... forEach loop to set all the params ... &lt;/c:when&gt; &lt;c:otherwise&gt; ... just set the param with key &amp; value ... &lt;/c:otherwise&gt; &lt;/c:choose&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload