I’m trying to build a url in a JSP from a Map<String, Object> of parameters. The existing code iterates through the map and adds c:params for the keys and values:
<c:url value="/">
<c:forEach items="${myParamMap}" var="parameter">
<c:param name="${parameter.key}" value="${parameter.value}" />
</c:forEach>
</c:url>
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:
<c:url value="/">
<c:forEach items="${myParamMap}" var="parameter">
<c:forEach items="${parameter.value}" var="innerValue">
<c:param name="${parameter.key}" value="${innerValue}" />
</c:forEach>
</c:forEach>
</c:url>
But of course this breaks the normal situation where the value is not iterable.
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: ${object.class.className == 'Whatever'}.
This does not work for arrays in JSTL because for the expression ${someArray.class}, JSTL tries to convert the .class part into an integer in order to use it as an index (I can’t believe someone thought this was a good idea).
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.
Using scriptlets is the way to go in this case. I ended up with something like:
<c:set var="val" value="${parameter.value}">
<% boolean isArray = pageContext.getAttribute("val").getClass().isArray(); %>
<c:choose>
<c:when test="<%= isArray >">
... forEach loop to set all the params ...
</c:when>
<c:otherwise>
... just set the param with key & value ...
</c:otherwise>
</c:choose>
Open a jsp scriptlet
<% ... %>. In this non standard situations I believe it is better use directly Java language.For example you can use scriptlet inside params too:
or
Remember that if you want to use
ain scriptlet you have to get it from pageContext, for example: