1

I'm refactoring 12 identical HTML form controls into a single piece of code inside a loop. I can't just loop the form because monthly values may or may not be present yet so I've built a month variable in the 1-12 range (so far so good):

<c:forEach var="month" begin="1" end="12">
    Month #<c:out value="${month}"/>
</c:forEach>

Now I need to access items from two hashmaps:

HashMap<Long, String> amounts
HashMap<String, String> invalidFields

The old "static" syntax was:

<c:out value="${it.amounts[1]}"/>
<c:out value="${it.invalidFields.amount_1}"/>

What's the syntax to inject month into the mix?

Álvaro González
  • 142,137
  • 41
  • 261
  • 360

1 Answers1

2

The begin and end of <c:forEach> are interpreted as java.lang.Integer, but your map keys are created as java.lang.Long.

Integer int1 = new Integer(1);
Long long1 = new Long(1L);
System.out.println(int1.equals(long1)); // false

So the Map#get() will never work for these keys.

Fix your amounts to be Map<Integer, String> instead, or use a List<String> instead.

Either way, then you can use:

${it.amounts[month]}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Totally right, I was in fact using the correct syntax but types didn't match. And as for the other hash map, I can also use square brackets so it's a matter of concatenating with `${'amount_'}${month}` into in a new variable and using that variable inside the brackets. – Álvaro González Jul 22 '20 at 07:18