Strange events encountered by C tag traversing map

Keywords: JSP

[data source]

  1. map stores common basic data types, such as String, key,value
Map<Integer, String> commonMap = new HashMap<Integer, String>();

commonMap.put(1,"aaa");
commonMap.put(2,"bbb");
commonMap.put(3,"ccc");
  1. The data type of map in the second, where value is an object

For example:

Map<Integer, StudentBean> specialMap = new HashMap<Integer, StudentBean>();

StudentBean s1 = new StudentBean();
StudentBean s2 = new StudentBean();

s1.setName("aaa");
s1.setAge(12);
s2.setName("bbb");
s3.setAge(14);

specialMap.put(1,s1);
specialMap.put(2,s2);

After the data is sorted out, it is traversing

For a normal map, that is, the first map traversal

Method 1

<c:forEach items="${commonMap }" varStatus="status">
	<c:set var="index" value="${status.index}"/>
		<li id="attachOtherPath${index }">
		<div style="display: inline;">
		<img src=${pageContext.request.contextPath}/jsp/viewImage.jsp?imgPath=<c:out value='${commonMap[index]}'/>  height="80" width="80" id="commonMap{index}"
		onclick="PreviewImg(this);" />
		</div>
	</li>
</c:forEach>

Method two

<c:forEach items="${commonMap }" varStatus="status" var="common">
	<c:set var="index" value="${status.index}"/>
		<li id="commonMap{index }">
		<div style="display: inline;">
		<img src=${pageContext.request.contextPath}/jsp/viewImage.jsp?imgPath=<c:out value='${common.value}'/>  height="80" width="80" id="commonMap{index}"
		onclick="PreviewImg(this);" />
		</div>
	</li>
</c:forEach>

In this case, you can get it directly without defining var.

There are two ways to get values. The first is to directly use commonmap as a variable to get data through commonMap[index], and the second is to define a cyclic variable

For the map of stored objects

Method one is not easy to use, only the way to define variables

<c:forEach items="${specialMap }" varStatus="status" var="special">
	<c:set var="index" value="${status.index}"/>
		<li id="specialMap{index }">
		<div style="display: inline;">
		<img src=${pageContext.request.contextPath}/jsp/viewImage.jsp?imgPath=<c:out value='${specialMap.value.name}'/>  height="80" width="80" id="specialMap{index}"
		onclick="PreviewImg(this);" />
		</div>
	</li>
</c:forEach>

Summary: in the future, if you encounter the problem of C tag traversal, you can define a variable directly, so that no other problems will occur.


Posted by mysoogal on Fri, 03 Apr 2020 13:01:16 -0700