后端传送一个带List的Map参数返回前台,当使用thymeleaf的th:each tag进行嵌套输出时发现内循环无法正确获取到数据。
后台传输对象:
@RequestMapping
public ModelAndView show(HttpServletRequest req, HttpServletResponse resp, Model model){
Map<String,Object> file = new HashMap<>();
List<FileInfo> AA = Arrays
.asList(new FileInfo("A1CLASS","A1ID","A1PATH","A1NAME"),
new FileInfo("A2CLASS","A2ID","A2PATH","A2NAME"),
new FileInfo("A3CLASS","A3ID","A3PATH","A3NAME"));
List<FileInfo> BB = Arrays
.asList(new FileInfo("B1CLASS","B1ID","B1PATH","B1NAME"),
new FileInfo("B2CLASS","B2ID","B2PATH","B2NAME"),
new FileInfo("B3CLASS","B3ID","B3PATH","B3NAME"));
file.put("AA",AA);
file.put("BB",BB);
ModelAndView modelAndView = new ModelAndView("ia11/ia1101/ia1101");
model.addAttribute("file",file);
model.addAttribute("test","test");
return modelAndView;
}
然后在前端使用<div th:text></div>标签查看输出内容。
具体HTML代码:
<div id="outDiv" th:each="map:${file}">
<div class="form-group">
<label id="lable" class="col-md-2">EACH</label>
<div id="document" class="col-md-10">
<div th:text="${map}"></div>
//in this time the th:each tag is useful
<div th:each="oneFile:${map}">
<div th:text="${oneFile}"></div>
// but in this time the th:each tag can't loop the FileInfo object in the AA
<input type="hidden" name="filesData_CLASS" th:value="${oneFile.fileClass}">
<input type="hidden" name="filesData_FILE_ID" th:value="${oneFile.fileId}">
<input type="hidden" name="filesData_PATH" th:value="${oneFile.filePath}">
<div class="input-group">
<input type="text" class="form-control" readonly name="fileChoose_text" th:value="${oneFile.fileName}">
<span class="input-group-btn">
<button type="button" name="fileChoose_btn" class="btn btn-default btn-flat" style="width:80px;height:34px;">选择</button>
</span>
</div>
</div>
</div>
</div>
</div>
在第一个each的时候是可以正常运作的,但是第二个each就能循环了。
在网上用各种姿势搜索都没找到结果,于是我去官方的github上提问了。
官方的回答如下:
When using th:each over Maps, then the value being iterated over is a java.util.Map.Entry type, so when doing your second th:each you need to extract the lists out of the map entry’s value property. So I think something like this will work:
还给出了例子:
<div th:each="mapEntry: ${file}">
<div th:each="fileInfo: ${mapEntry.value}">
<input type="text" class="form-control" readonly name="fileChoose_text" th:value="${fileInfo.fileName}">
...
</div>
</div>
大致意思是 在使用th:each循环map时,他迭代的是Map.Entry所以在第二个循环的时候其实是map的一对键值对,不是只有值得一个List,所以我们需要获取键值对的值,对于值去进行循环。