Home > other >  JSP how to concat value in name attribute?
JSP how to concat value in name attribute?

Time:02-20

Here is what I use in Thymeleaf. I just concat dishIdQuantityMap with dish.id.

        <div  th:each="dish : ${dishList}">
                              <input
                            th:value="0"
                            th:name="${'dishIdQuantityMap['   dish.id   ']'}"
                            type="number"
                            min="0"
                            max="100"
                            step="1"
                            readonly
                    />

And it works fine, but if I do the same in JSP

   <input
                                value="0"
                                name="${'dishIdQuantityMap['   dish.id   ']' }"
                                type="number"
                                min="0"
                                max="100"
                                step="1"
                                readonly
                        />

It fails. Exception happens on line 142 enter image description here What do I do wrong?

Caused by: java.lang.NumberFormatException: For input string: "dishIdQuantityMap"

UPD. If I do it like this, it kinda works

name="${'dishIdQuantityMap['}${dish.id}${']'}"

CodePudding user response:

I think you have too many quotes. Here is a demonstration JSP.

<%@ page import="java.util.HashMap, java.util.ArrayList"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
    ArrayList<String> list = new ArrayList<String>();
    list.add("a");
    list.add("b");
    list.add("c");
    pageContext.setAttribute("list", list);
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("a", 11);
    map.put("b", 22);
    map.put("c", 33);
    pageContext.setAttribute("map", map);
%>
<c:forEach items="${map}" varStatus="loopCount">
    ${map[list[loopCount.index]]}
</c:forEach>

The output is 11 22 33 . You could try using name="${dishIdQuantityMap[dish.id]}" As Jeka_FRIZZ pointed out dish must be in scope.

  • Related