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

Thymeleaf中textarea的th:field失效问题求助

Thymeleaf中textarea的th:field失效问题解决

问题原因

你用th:field="*{description}"时,Thymeleaf会自动绑定**当前上下文的表单对象(也就是你存在model里的post)**的description属性,但你的多语言描述是单独存到model里的${description},并不是post对象的属性,所以th:field找不到对应值,自然失效。而input能正常工作,是因为你直接通过th:value="${description}"取了model里的单独属性,还指定了name,POST时能正常提交参数。

解决方案

方案1:调整表单对象绑定(保留th:field)

如果一定要用th:field,需要把多语言描述放到表单对象里。在Controller里修改代码,把获取到的多语言描述赋值给post对象:

@GetMapping("/{language}/post/{id}/edit")
public String editPost(@PathVariable Language language,
                       @PathVariable Long id,
                       Model model) throws Exception {
    Post post = postService.getPost(id);
    String description = postService.getDescription(id, language);
    post.setDescription(description); // 将多语言描述设置到post对象中
    model.addAttribute("post", post);
    model.addAttribute("language", language.getCode());
    return "admin/post-edit";
}

这样th:field="*{description}"就能正确绑定到post的description属性,显示多语言内容,同时Thymeleaf会自动生成正确的name属性,POST时也能正常提交数据。

方案2:直接绑定model属性(不用th:field)

如果不想修改表单对象,直接给textarea设置name和内容即可,和你能用的input写法逻辑一致:

<label>Description</label>
<textarea id="description" name="description" placeholder="Enter content" th:text="${description}">
</textarea>

或者用Thymeleaf内联表达式更直观:

<label>Description</label>
<textarea id="description" name="description" placeholder="Enter content">
[[${description}]]
</textarea>

这样既能正确显示多语言描述,name属性也和input保持一致,POST请求能正常完成数据更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 08:47:19