You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Thymeleaf中使用变量作为Key直接获取Map的对应值

你尝试的写法失效核心原因是类型不匹配:控制器中student Map的key是Integer类型,但你存入Model的rollNo是String类型,二者类型不一致无法匹配到对应key。同时注意SpEL表达式中同一个${}块内部直接引用变量即可,不需要嵌套${},嵌套写法本身不符合语法规则。


方案1(更推荐):对齐变量类型

修改控制器代码,把rollNo的类型调整为和Map key一致的Integer:

Map<Integer, String> student = new HashMap<>();
student.put(1,"Kiran");

// 原代码 String rollno= 1; 替换为以下内容
Integer rollNo = 1;

model.addAttribute("student", student);
model.addAttribute("rollNo", rollNo);

修改完成后以下两种写法均可正常生效:

<!-- get方法写法 -->
<span th:text="${student.get(rollNo)}"></span>
<!-- 数组访问式写法,更简洁 -->
<span th:text="${student[rollNo]}"></span>

方案2:无需修改控制器,Thymeleaf层做类型转换

如果需要保留rollNo为String类型,可在Thymeleaf中先将rollNo转为Integer再取值:

<!-- 使用Thymeleaf内置的numbers工具类做类型转换 -->
<span th:text="${student[#numbers.parseInt(rollNo)]}"></span>

内容的提问来源于stack exchange,提问作者kiran ugalmugale

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 00:15:09