Thymeleaf遍历List<String>/String[]无数据显示问题求助
Thymeleaf遍历List/String[]无内容显示问题
我在使用Thymeleaf模板时,尝试遍历List<String>或String[]类型的files数据,但页面始终无内容显示。我确认迭代语法是正确的,且后端Controller返回视图前,Model中已包含有效的files数据,切换两种数据类型后问题仍存在。
模板代码片段
<tr th:each="file : ${files}"> <td> <a target="_blank" class="btn btn-success" th:href="@{/home/get-file/{file}(file = ${file})}">查看</a> <a class="btn btn-danger" th:href="@{/home/delete-file/{file}(file = ${file})}">删除</a> </td> <th scope="row" th:text="${file}">示例文件.txt</th> </tr>
无论files是String[]还是List<String>类型,页面都无法渲染出对应内容。
后端代码实现
Controller层
@PostMapping("/upload") public String handleFileUpload(@RequestParam("fileUpload") MultipartFile file, Model model) throws IOException { fileService.addFile(SecurityContextHolder.getContext().getAuthentication(), file, model); return "result"; }
Service层
public int addFile(Authentication authentication, MultipartFile multipartFile, Model model) throws IOException { String userName = authentication.getName(); User user = userMapper.getUser(userName); Integer userId = user.getUserId(); String fileName = multipartFile.getOriginalFilename(); if (!fileIsDuplicate(userId, fileName)) { try { byte[] fileData = multipartFile.getBytes(); String contentType = multipartFile.getContentType(); String fileSize = String.valueOf(multipartFile.getSize()); File file = new File(fileName, contentType, fileSize, (long)userId, fileData); int id = fileMapper.insertFile(file); model.addAttribute("files", fileMapper.getFilesByUserId(userId).toArray(new String[0])); model.addAttribute("result", "success"); return id; } catch (IOException e) { e.printStackTrace(); model.addAttribute("result", "error"); model.addAttribute("message", "保存文件时发生异常。"); return -1; } } model.addAttribute("result", "error"); model.addAttribute("message", "你尝试添加的文件已存在。"); return -1; }
排查情况说明
调试时已确认,Controller返回视图前,Model中已包含有效的files数据,但页面就是无法渲染出迭代内容。
内容的提问来源于stack exchange,提问作者asd
相关产品推荐
相关产品推荐

