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

Thymeleaf+Spring打印类内List字段值遇SpEL异常求助

解决SpringEL无法找到List字段的问题

你遇到的这个SpEL异常,核心原因有两个:

  1. 你在Thymeleaf里用T(com.example.test.ResponseObject).iWantIt试图访问类的静态属性,但你的iWantIt是ResponseObject的实例字段(非静态),而且还写错了类的全路径——模型里的类是com.example.test.model.ResponseObject,视图里少了model包路径。
  2. T()是SpEL用来访问类静态成员、方法或做类型转换的语法,用它访问实例字段本身就是错误用法。

下面是具体的修复步骤:

第一步:确保Controller把ResponseObject实例传入Model

因为你的ResponseObject加了@Component注解,可以直接注入到Controller里,然后把实例放到Model中供视图调用:

@Controller
public class TestController {
    @Autowired
    private ResponseObject responseObject;

    @GetMapping("/your-page")
    public String showPage(Model model) {
        // 这里模拟给List赋值(你已经确认过赋值逻辑没问题)
        responseObject.setIWantIt(Arrays.asList(10, 20, 30));
        // 将实例存入Model,命名为responseObj
        model.addAttribute("responseObj", responseObject);
        return "your-view-name";
    }
}

第二步:修正Thymeleaf视图代码

现在可以直接引用Model里的实例对象,访问它的iWantIt字段了,同时建议加上非空+非空列表的判断:

<div th:if="${responseObj.iWantIt != null and !responseObj.iWantIt.isEmpty()}">
    <ul th:each="wantedItem : ${responseObj.iWantIt}">
        <li th:text="${wantedItem}"/>
    </ul>
</div>

额外优化建议

虽然你的iWantIt是public字段,但更符合Java规范的写法是用private字段+getter方法。如果改成private字段,只要你有对应的getIWantIt()方法,Thymeleaf的SpEL会自动识别并调用getter,视图里的写法不需要改动。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:23:54