Get the class name of an array in JSTL

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>

Answers


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:

<c:set var="className" value="<%= ... get class name ... %>" /> 

or

<c:set var="isArray" value="<%= a.getClass().isArray() %>" />

Remember that if you want to use a in scriptlet you have to get it from pageContext, for example:

<% Object a = pageContext.getParameter("innerValue"); %>

Need Your Help

Could I create a global namespace hierarchy in C++ that is similar to C#'s to assist developers using our code?

c# c++ ide slickedit

Is it possible to create a namespace hierarchy in C++ that resembles how it works in C#. For instance if I were to need a type to deal colors within C#, I could dive down through the namespaces to ...

Why do I need to include <stdio.h> to use CUDA's printf()?

c++ cuda printf gpu-programming

I want to printf() something in my CUDA kernel. [The Programming Guide suggests][1] I do this like so: